首页 > 其他 > 详细

Leetcode.25. Reverse Nodes in k-Group

时间:2018-09-22 20:48:34      阅读:233      评论:0      收藏:0      [点我收藏+]

题意:链表翻转,每k个翻一次,最后不足k个的不翻

题解:没啥难点,就是要对逻辑有一点要求;当然你也可以先存到数组里,然后用数学方法计算下标进行swap,但是这脱离了这道题的本意,代码不放了

技术分享图片
 1 class Solution {
 2 public:
 3     void reverse(vector<ListNode*>& lists) {
 4         for (auto i = 0; i < lists.size() - 1; i++) {
 5             ListNode *st = lists[i], *ed = lists[i + 1];
 6             ListNode *cur = st, *nex = st->next, *tmp;
 7             while (nex != ed) {
 8                 tmp = nex->next;
 9                 nex->next = cur;
10                 cur = nex;
11                 nex = tmp;
12             }
13             st = cur;
14             lists[i] = st;
15         }
16         for (auto i = 0; i < lists.size() - 1; i++) {
17             ListNode *st = lists[i], *ed = lists[i + 1];
18             while (st->next->next != st) st = st->next;
19             st->next->next = ed;
20         }
21         return;
22     }
23     
24     ListNode* reverseKGroup(ListNode* head, int k) {
25         if (head == NULL || k <= 1)
26             return head;
27         vector<ListNode*> lists;
28         ListNode* p = head;
29         int cnt = 0;
30         while (p != NULL)
31         {
32             for (auto i = 0; i < k && p != NULL; i++) {
33                 if (i == 0)
34                     lists.push_back(p);
35                 cnt++;
36                 p = p->next;
37             }
38         }
39         if (cnt % k == 0)
40             lists.push_back(NULL);
41         reverse(lists);
42         return lists[0];
43     }
44 };
View Code

 

Leetcode.25. Reverse Nodes in k-Group

原文:https://www.cnblogs.com/hexsix/p/9691007.html

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