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
”的升级版,同时增加了链表逆序输出的功能,重点除了链表逆转之外,还要注意如果剩余的节点数小于k的话,剩余的节点就不要逆序了,剩余的节点仍按照原顺序输出,以下是Java解题代码:
public static ListNode returnNextNode(ListNode head, int k){
//输入当前节点和k值,返回下一次循环的节点,即从当前节点向后的第k个节点,
//若在寻找过程中链表结束,则返回输入的节点
if(head==null)
return head;
ListNode current=head;
ListNode temp = head;
int i=0;
while(i<k){
temp=temp.next;
++i;
if(temp==null)
return current;
}
return temp;
}
public static void reverseLink(ListNode head, int k,ListNode finish){
//输入当前节点、k值和当前节点将要指向的节点,将该段链表逆转
ListNode current = head;
ListNode myNext = head.next;
current.next=finish;
if(k==2)
myNext.next=current;
else if(k>2){
ListNode myThird = myNext.next;
int i = 0;
while(i+2<k&&myThird!=null){
myNext.next=current;
current=myNext;
myNext=myThird;
myThird=myThird.next;
i++;
}
myNext.next=current;
}
}
public static ListNode reverseKGroup(ListNode head, int k) {
ListNode myNext=returnNextNode(head,k);
ListNode myFinish=returnNextNode(head,k-1);
if(head==myFinish)
return head;
ListNode result = myFinish;
ListNode current=head;
while(current!=myNext){
myFinish = returnNextNode(myNext,k-1);
reverseLink(current, k,myFinish);
current=myNext;
myNext=returnNextNode(current,k);
}
if(myFinish!=current){
reverseLink(current, k,null);
}
return result;
}