forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0025-reverse-nodes-in-k-group.java
81 lines (67 loc) · 1.87 KB
/
0025-reverse-nodes-in-k-group.java
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
76
77
78
79
80
81
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
//This recursive approach is super intuitive taken from leetcode discuss.
// Time Complexity: O(n)
// Extra Space Complexity: O(n)
class Solution1 {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode cur = head;
int count = 0;
while (cur != null && count != k) {
cur = cur.next;
count++;
}
if (count == k) {
cur = reverseKGroup(cur, k);
while (count-- > 0) {
ListNode temp = head.next;
head.next = cur;
cur = head;
head = temp;
}
head = cur;
}
return head;
}
}
// An iterative approach
// Time Complexity: O(n)
// Extra Space Complexity: O(1)
class Solution2 {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0, head);
ListNode curr = head;
ListNode prev = dummy;
ListNode temp = null;
int count = k;
while (curr != null) {
if (count > 1) {
temp = prev.next;
prev.next = curr.next;
curr.next = curr.next.next;
prev.next.next = temp;
count--;
} else {
prev = curr;
curr = curr.next;
ListNode end = curr;
for (int i = 0; i < k; ++i) {
if (end == null) {
return dummy.next;
}
end = end.next;
}
count = k;
}
}
return dummy.next;
}
}