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

 

 1 public class Solution {
 2     public ListNode reverseKGroup(ListNode head, int k) {
 3         if(head==null||k==1) return head;
 4         int len =0;
 5         ListNode pre = head;
 6         while(pre!=null){
 7             len++;
 8             pre = pre.next;
 9         }
10         int times = len/k;
11         ListNode cur =head,post=head.next;
12         ListNode safe = new ListNode(-1);
13         safe.next = head;
14         pre = safe;
15         for(int i=0;i<times;i++){
16             for(int j=0;j<k-1;j++){
17                 ListNode temp = post.next;
18                 post.next = cur;
19                 cur = post;
20                 post = temp;
21             }
22             ListNode temp = pre.next;
23             pre.next = cur;
24             temp.next = post;
25             pre = temp;
26             cur = post;
27             if(post!=null)
28                 post = post.next;
29         }
30         return safe.next;
31     }
32 }
View Code

 

 

 

posted @ 2014-02-06 13:59  krunning  阅读(236)  评论(0编辑  收藏  举报