Leetcode.25. Reverse Nodes in k-Group

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

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

 1 class Solution {
 2 public:
 3     void reverse(vector& 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 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

 

转载于:https://www.cnblogs.com/hexsix/p/9691007.html

你可能感兴趣的:(Leetcode.25. Reverse Nodes in k-Group)