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

leetcode25 K个一组翻转链表

时间:2021-04-26 13:49:52      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:eve   rgba   style   list   span   ==   nod   思路   rgb   

思路:

模拟。

实现:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode() : val(0), next(nullptr) {}
 7  *     ListNode(int x) : val(x), next(nullptr) {}
 8  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 9  * };
10  */
11 class Solution
12 {
13 public:
14     ListNode* reverse(ListNode* head)
15     {
16         if (head == NULL or head->next == NULL) return head;
17         ListNode* pre = head, *cur = head->next;
18         head->next = NULL;
19         while (cur)
20         {
21             ListNode* nxt = cur->next;
22             cur->next = pre;
23             pre = cur;
24             cur = nxt;
25         }
26         return pre;
27     }
28     ListNode* reverseKGroup(ListNode* head, int k)
29     {
30         ListNode* cur = head, *cur_head = head, *res = NULL, *last_tail = NULL;
31         int cnt = 1;
32         while (cur)
33         {
34             if (cnt % k == 0)
35             {
36                 ListNode* next_head = cur->next;  
37                 cur->next = NULL;
38                 ListNode* new_head = reverse(cur_head);
39                 if (res == NULL) res = new_head;
40                 if (last_tail) last_tail->next = new_head; 
41                 cur_head->next = next_head;
42                 last_tail = cur = cur_head;
43                 cur_head = cur->next;
44             }
45             cnt++;
46             cur = cur->next;
47         }
48         return res ? res: head;
49     }
50 };

leetcode25 K个一组翻转链表

标签:eve   rgba   style   list   span   ==   nod   思路   rgb   

原文地址:https://www.cnblogs.com/wangyiming/p/14700327.html

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