题目
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
思路
这道题是Swap Nodes in Pairs的变种,基本思路一样,只不过每次reverse k个节点,用一个数组来存储这些节点,reverse完成后向后移动k个节点的距离。
代码
/**
* 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(k < 2)
return head;
ListNode[] nodes = new ListNode[k];
ListNode current = head;
shiftNodes(nodes, current);
for(int i = 0; i < k; i++){
if(current == null)
return head;
nodes[i] = current;
current = current.next;
}
ListNode pre = new ListNode(-1);
pre.next = nodes[0];
head = nodes[k-1];
while(nodes[k-1] != null) {
reverseNodes(nodes);
pre.next = nodes[k-1];
pre = nodes[0];
shiftNodes(nodes,pre.next);
}
return head;
}
public void reverseNodes(ListNode[] nodes) {
int k = nodes.length;
nodes[0].next = nodes[k-1].next;
for(int i = k - 1; i > 0; i--) {
nodes[i].next = nodes[i-1];
}
}
public void shiftNodes(ListNode[] nodes, ListNode current) {
int k = nodes.length;
for(int i = 0; i < k; i++) {
if(current == null) {
nodes[k-1] = null;
return;
}
nodes[i] = current;
current = current.next;
}
}
}