-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathReverseNodesinkGroup.java
57 lines (44 loc) · 1.17 KB
/
ReverseNodesinkGroup.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
/**
* 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; }
* }
*/
class Solution {
// TC : O(n)
// SC : O(1)
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || k ==1) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
int totalNodes = 0;
ListNode curr = head;
// counts the total no of nodes
while(curr!= null){
totalNodes++;
curr = curr.next;
}
curr = head;
ListNode next = null;
ListNode prev = dummy;
while(totalNodes>=k){
curr = prev.next;
next = curr.next;
for(int i=1;i<k;i++) {// k-1 times
curr.next = next.next;
next.next = prev.next;
prev.next = next;
next = curr.next;
}
prev = curr;
totalNodes = totalNodes - k;
}
return dummy.next;
}
}