@@ -2271,7 +2271,38 @@ \subsubsection{分析}
2271
2271
\subsubsection {代码 }
2272
2272
\begin {Code }
2273
2273
// LeetCode, Reverse Nodes in k-Group
2274
- // 时间复杂度O(n),空间复杂度O(1)
2274
+ // 递归版,时间复杂度O(n),空间复杂度O(1)
2275
+ class Solution {
2276
+ public:
2277
+ ListNode *reverseKGroup(ListNode *head, int k) {
2278
+ if (head == nullptr || head->next == nullptr || k < 2)
2279
+ return head;
2280
+
2281
+ ListNode *next_group = head;
2282
+ for (int i = 0; i < k; ++i) {
2283
+ if (next_group)
2284
+ next_group = next_group->next;
2285
+ else
2286
+ return head;
2287
+ }
2288
+ // next_group is the head of next group
2289
+ // new_next_group is the new head of next group after reversion
2290
+ ListNode *new_next_group = reverseKGroup(next_group, k);
2291
+ ListNode *prev = NULL, *cur = head;
2292
+ while (cur != next_group) {
2293
+ ListNode *next = cur->next;
2294
+ cur->next = prev ? prev : new_next_group;
2295
+ prev = cur;
2296
+ cur = next;
2297
+ }
2298
+ return prev; // prev will be the new head of this group
2299
+ }
2300
+ };
2301
+ \end {Code }
2302
+
2303
+ \begin {Code }
2304
+ // LeetCode, Reverse Nodes in k-Group
2305
+ // 迭代版,时间复杂度O(n),空间复杂度O(1)
2275
2306
class Solution {
2276
2307
public:
2277
2308
ListNode *reverseKGroup(ListNode *head, int k) {
@@ -2330,7 +2361,7 @@ \subsubsection{分析}
2330
2361
\subsubsection {代码 }
2331
2362
\begin {Code }
2332
2363
// LeetCode, Copy List with Random Pointer
2333
- // 两遍扫描
2364
+ // 两遍扫描,时间复杂度O(n),空间复杂度O(1)
2334
2365
class Solution {
2335
2366
public:
2336
2367
RandomListNode *copyRandomList(RandomListNode *head) {
0 commit comments