码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Reverse Nodes in k-Group 解题报告

时间:2014-10-20 14:46:35      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   os   ar   使用   

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. 用递归实现,逐层进行反转。遇到最后一个如果个数不为k,再反转一次即可。
bubuko.com,布布扣View Code

2. 使用一个专用的反转函数来进行反转,从头到尾遍历,遍历到K的时候,使用Pre-Next指针的方式进行反转。这个方法比递归更棒。

 1 /*
 2      * Solution 2:
 3      * 使用区间反转的办法, iteration.
 4      * */
 5     public ListNode reverseKGroup(ListNode head, int k) {
 6         if (head == null) {
 7             return null;
 8         }
 9         
10         ListNode dummy = new ListNode(0);
11         dummy.next = head;
12         
13         ListNode cur = head;
14         ListNode pre = dummy;
15         
16         int cnt = 0;
17         
18         while (cur != null) {
19             cnt++;
20             if (cnt == k) {
21                 cnt = 0;
22                 pre = reverse(pre, cur.next);
23             }
24             cur = cur.next;
25         }
26         
27         return dummy.next;
28     }
29     
30     /**
31      * Reverse a link list between pre and next exclusively
32      * an example:
33      * a linked list:
34      * 0->1->2->3->4->5->6
35      * |           |   
36      * pre        next
37      * after call pre = reverse(pre, next)
38      * 
39      * 0->3->2->1->4->5->6
40      *          |  |
41      *          pre next
42      * @param pre 
43      * @param next
44      * @return the reversed list‘s last node, which is the precedence of parameter next
45      */
46     private static ListNode reverse(ListNode pre, ListNode next){
47         ListNode cur = pre.next;
48         
49         // record the new tail.
50         ListNode last = cur;
51         while (cur != next) {
52             ListNode tmp = cur.next;
53             cur.next = pre.next;
54             pre.next = cur;
55             cur = tmp;
56         }
57         
58         last.next = next;
59         return last;
60     }

主页君的GitHub代码

ref: http://www.cnblogs.com/lichen782/p/leetcode_Reverse_Nodes_in_kGroup.html

LeetCode: Reverse Nodes in k-Group 解题报告

标签:des   style   blog   http   color   io   os   ar   使用   

原文地址:http://www.cnblogs.com/yuzhangcmu/p/4037039.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!