Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked 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
题目分析:把上一题的两两倒置,改成了n(n>0)倒置,其他不变。
题目思路:用缓冲区来暂存要倒置的一堆节点的引用,没啥技术含量。引用的理解正确,就不会错。
import java.lang.Math;
import java.util.Arrays;
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public ListNode reverseKGroup(ListNode head,int k) {
if(k==1)return head; //如果倒置数为1,就是啥都不变,直接返回
ListNode[] circle=new ListNode[k+1]; //新建k+1大小的buffer,保存要倒置的节点引用
circle[0]=new ListNode(0); //LeetCode里的链表从第一个节点就是开始保存数据了,所以要新建一个节点来抓住输入链表的头。
circle[0].next=head;
ListNode Pchild=head;
head=circle[0]; //把head重定义了,haed不是head了
int i=1;
while(Pchild!=null){ //只要还没扫到链表末尾
if(i!=k){
circle[i]=Pchild; //没扫满一组,就把节点引用给buffer
}else{
circle[i]=Pchild.next; //保存下一轮的首个节点
circle[0].next=Pchild; //上一轮最后一个节点的next赋为Pchild
int j=0;
for(j=k-1;j>0;j--){
Pchild.next=circle[j];
Pchild=circle[j];
}//把buffer里的next引用都改过来
circle[j+1].next=circle[k];//最后一个next指向下一组的首个节点
circle[0]=Pchild=circle[j+1];//本组最后一个节点赋给circle[0]和Pchild保证循环正确
i=0;
}
Pchild=Pchild.next;
i++;
}
return head.next;
}
}