Leetcode.25. Reverse Nodes in k-Group

Posted hexsix

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode.25. Reverse Nodes in k-Group相关的知识,希望对你有一定的参考价值。

题意:链表翻转,每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的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 25:Reverse Nodes in k-Group

LeetCode 25. Reverse Nodes in k-Group

leetcode25. Reverse Nodes in k-Group

leetcode 25 Reverse Nodes in k-Group

LeetCode 25: Reverse Nodes in k-Group

[LeetCode]25. Reverse Nodes in k-Group k个一组翻转链表