import java.util.Scanner;
// 定义链表节点类
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取输入的第一行,构建链表
String[] values = scanner.nextLine().split(" ");
ListNode head = buildLinkedList(values);
// 读取输入的 k 值
int k = scanner.nextInt();
// 每 k 个节点一组翻转链表
head = reverseKGroup(head, k);
// 输出翻转后的链表
printLinkedList(head);
}
// 根据字符串数组构建链表
private static ListNode buildLinkedList(String[] values) {
if (values == null || values.length == 0) {
return null;
}
ListNode dummy = new ListNode(-1);
ListNode current = dummy;
for (String value : values) {
current.next = new ListNode(Integer.parseInt(value));
current = current.next;
}
return dummy.next;
}
// 每 k 个节点一组翻转链表
private static ListNode reverseKGroup(ListNode head, int k) {
if (head == null || k <= 1) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
int n = 0;
ListNode tmp = head;
while (tmp != null) {
++n;
tmp = tmp.next;
}
// int t = n % k;
ListNode p0 = dummy;
// for (int i = 1; i <= t; ++i) {
// p0 = p0.next;
// }
// int len = n - t;
int len = n;
ListNode pre = null;
ListNode cur = p0.next;
while (len >= k) {
len -= k;
for (int i = 1; i <= k; ++i) {
ListNode nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
ListNode nxt = p0.next;
p0.next.next = cur;
p0.next = pre;
p0 = nxt;
}
return dummy.next;
}
// 打印链表
private static void printLinkedList(ListNode head) {
while (head != null) {
System.out.print(head.val);
if (head.next != null) {
System.out.print(" ");
}
head = head.next;
}
System.out.println();
}
}