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
楼主在EMC面试的时候曾经遇到过这题,当时觉得题目很复杂,后来发现竟然是LeetCode上的原题,题目思路其实还是很容易得到的,但是细节很多,因此把辅助函数单独写出来,可以简化算法
public static void solution_2_2_9(Node head,int k){
Node p1=head,p2=head,temp=null,pre=null,nextEnd=null,h2=null;
int i=0;
while(p2!=null){
for(i=1;i<k;i++){
p2=p2.next;
if(p2==null)
break;
}
if(i==k){
temp=p2.next;
nextEnd=temp;
Node h=reverse(p1,p2,nextEnd);
if(pre!=null){
pre.next=h;
pre=p1;
}
else{
h2=h;
pre=p1;
}
p1=temp;p2=p1;
}
}
for(Node r=h2;r!=null;r=r.next){
System.out.print(r.data+" ");
}
}
private static Node reverse(Node begin,Node end,Node nextEnd){
Node pre=null,t=begin,h=null,q=null;
while(t!=nextEnd){
q=t.next;
if(t==end){
h=end;
}
if(pre==null){
pre=t;
pre.next=nextEnd;
}
else{
t.next=pre;
pre=t;
}
t=q;
}
return h;
}