如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
给定这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
第一行:依次输入链表中的各个元素,以"#"结束
第二行:每组数量k
处理后的链表中的各个元素,以"->"连接
1 2 3 4 5 # 2
2->1->4->3->5
1 2 3 4 5 # 3
3->2->1->4->5
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
static class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String arrayStr = in.nextLine();
int k = in.nextInt();
ListNode head = new ListNode(0);
ListNode p = head;
String[] array = arrayStr.split(" ");
for (int i = 0; i < array.length - 1; i++) {
p.next = new ListNode(Integer.parseInt(array[i]));
p = p.next;
}
// 反转链表
head = reverseK(head.next, k);
printList(head);
}
}
private static ListNode reverseK(ListNode head, int k) {
// 如果反向反转 此处需要将整个链表反转
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
ListNode end = dummy;
// 循环操作
while (end.next != null) {
for (int i = 0; i < k && end != null; i++) {
end = end.next;
}
if (end == null) {
break;
}
// 开始切断连线
ListNode start = pre.next;
ListNode nextStart = end.next;
end.next = null;
pre.next = reverseKGroup(start);
start.next = nextStart;
pre = start;
end = pre;
}
return dummy.next;
}
// 反转链表 改变指针方向
private static ListNode reverseKGroup(ListNode head) {
ListNode pre = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next ;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}
/**
* 2->1->4->3->5
*/
private static void printList(ListNode head) {
StringBuilder sd = new StringBuilder();
while (head != null) {
sd.append(head.val);
head = head.next;
if (head != null ) {
sd.append("->");
}
}
System.out.println(sd.toString());
}
}