首页 > 其他 > 详细

LeetCode之“链表”:Reverse Nodes in k-Group

时间:2015-06-27 15:18:47      阅读:224      评论: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

  这道题个人想法是将链表分段求逆,然后再合并。具体程序如下(有点冗余,有些代码可以合并):

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* reverseList(ListNode* head, int k)
12     {
13         if(!head || !head->next)
14             return head;
15             
16         int len = 0;
17         ListNode *start = head;
18         while(start)
19         {
20             len++;
21             start = start->next;
22             if(len == k)
23                 break;
24         }
25         if(len < k)
26             return head;
27         
28         ListNode *postList = start;
29         start = head;
30         ListNode *prev = nullptr;
31         while(start != postList)
32         {
33             ListNode *next = start->next;
34             start->next = prev;
35             prev = start;
36             start = next;
37         }
38         
39         start = prev;
40         while(start->next)
41             start = start->next;
42         start->next = postList;
43         
44         return prev;
45     }
46 
47     ListNode* reverseKGroup(ListNode* head, int k) {
48         ListNode *dummy = new(nothrow) ListNode(INT_MIN);
49         assert(dummy);
50         dummy->next = head;
51         ListNode *preNode = dummy;
52         while(true)
53         {
54             preNode->next = reverseList(head, k);
55             head = preNode->next;
56             int cnt = 0;
57             while(head)
58             {
59                 cnt++;
60                 head = head->next;
61                 preNode = preNode->next;
62                 if(cnt == k)
63                     break;
64             }
65             
66             if(cnt < k)
67             {
68                 head = dummy->next;
69                 delete dummy;
70                 dummy = nullptr;
71                 return head;
72             }
73         }
74     }
75 };

 

LeetCode之“链表”:Reverse Nodes in k-Group

原文:http://www.cnblogs.com/xiehongfeng100/p/4603881.html

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