Question
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Solution
这道题并不难,但是比较繁琐。思路是两步走:
1. 找出当前要反转的子序列
2. 反转子序列 (类比反转 m - n 那道题)
对要反转的子序列,我们用一头(prev)一尾(end)表示
prev -> 1 -> 2 -> 3 -> 4 -> end
如k=4,在help函数中,我们定义cur = prev.next, then = cur.next 循环结束条件是then != end。最后返回新序列的尾指针,即下一个要反转序列的prev指针,该例子中为4。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || k == 0 || k == 1) {
return head;
}
ListNode dummy = new ListNode(-1);
ListNode prev = dummy;
dummy.next = head;
int i = 0;
while (head != null) {
i++;
if (i % k == 0) {
prev = reverse(prev, head.next);
head = prev.next;
} else {
head = head.next;
}
}
return dummy.next;
} private ListNode reverse(ListNode prev, ListNode end) {
ListNode cur = prev.next, head = prev.next;
ListNode then = cur.next;
cur.next = null;
ListNode tmp;
while (then != end) {
tmp = then.next;
then.next = cur;
cur = then;
then = tmp;
}
prev.next = cur;
head.next = end;
return head;
}
}