forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
25_Reverse_Nodes_in_k-Group
76 lines (67 loc) · 1.98 KB
/
25_Reverse_Nodes_in_k-Group
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
Leetcode 25: Reverse Nodes in k-Group
Detailed video explanation: https://youtu.be/BfQeP6XEXEc
========================================================
C++:
---
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(!head || !head->next || k == 1) return head;
int n = 0; // count
ListNode *curr = head;
while(curr){
n++;
curr = curr->next;
}
ListNode *prev = nullptr, *next, *newHead;
ListNode *t1 = nullptr, *t2 = head;
curr = head;
while(n >= k){
for(int i = 0; i < k; i++){
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
if(!newHead) newHead = prev;
if(t1) t1->next = prev;
t2->next = curr; // n is not multiple of k
t1 = t2;
t2 = curr;
prev = nullptr;
n -= k;
}
return newHead;
}
};
Python3:
-------
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if (head == None) or (head.next == None) or (k == 1): return head
n = 0 # count
curr = head
while curr != None:
n, curr = n+1, curr.next
prev, next, newHead = None, None, None
t1, t2 = None, head
curr = head
while n >= k:
for i in range(k):
next = curr.next
curr.next = prev
prev = curr
curr = next
if newHead == None: newHead = prev
if t1 != None: t1.next = prev
t2.next = curr # n is not multiple of k
t1 = t2
t2 = curr
prev = None
n -= k
return newHead