Reverse Nodes in k-Group
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
代码如下:
public ListNode reverseKGroup(ListNode head, int k) {
if(head==null||k==1){
return head;
}
ListNode l0 = head;
int len =0;
while(l0!=null){
len++;
l0=l0.next;
}
if(k>len){
k=len;
return head;
}
ListNode ls[] = new ListNode[len+1];
ListNode l1 = head;
int index =0;
int n = (len-len%k)/k;
while(index<len){//记录所有指针
ls[index] = l1;
l1 = l1.next;
index++;
}
ListNode l2 = ls[k-1];//0-k
for (int i = n; i >= 1; i--) {//从尾部开始做到头部
int g =i*k-1;
int d = k*(i-1);
while(g>=d){
if(g==d){
if((i+1)*k-1<len){
ls[g].next = ls[(i+1)*k-1];
}else{
ls[g].next = ls[i*k];
}
}else{
ls[g].next = ls[g-1];
}
g--;
}
}
return l2;
}