首页 > 其他 > 详细

Reverse Nodes in k-Group

时间:2014-02-06 15:59:27      阅读:390      评论:0      收藏:0      [点我收藏+]

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

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

Reverse Nodes in k-Group

原文:http://www.cnblogs.com/krunning/p/3538728.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!