-
Notifications
You must be signed in to change notification settings - Fork 6
/
ReverseNodesInKGroup.java
60 lines (46 loc) · 1.48 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
58
59
60
package com.shivaprasad.january.day20;
//Note: For Linked List problems, Just focus on method code because creating Linked List for every problem is a hectic task,
//and we don't need to worry about it.
//Problem Link: https://leetcode.com/problems/reverse-nodes-in-k-group/
public class ReverseNodesInKGroup {
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; }
}
public ListNode reverseKGroup(ListNode head, int k) {
return reverseNodesInKGroups(head,k);
}
public ListNode reverseNodesInKGroups(ListNode head, int k)
{
if(head == null)
return null;
ListNode curr = head;
int currLen = 1;
while(curr.next!=null && currLen<k)
{
curr = curr.next;
currLen++;
}
if(currLen < k)
return head;
ListNode tempNode = curr.next;
curr.next = null;
ListNode prev = null;
curr = head;
while(curr!=null)
{
ListNode tmp = curr.next;
curr.next = prev;
prev = curr;
curr = tmp;
}
ListNode tempList = reverseNodesInKGroups(tempNode,k);
head.next = tempList;
return prev;
//T.C: O(n)
//S.C: O(1) but auxiliary space takes by recursion call stack will be O(n/k) nothing but O(n)
}
}