forked from mevipinmaurya/hbtuHacktoberfest2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreversenodeKGroup.java
More file actions
35 lines (34 loc) · 935 Bytes
/
reversenodeKGroup.java
File metadata and controls
35 lines (34 loc) · 935 Bytes
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
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode curr = head;
int count = 0;
while (curr != null) {
count++;
curr = curr.next;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prevGroupTail = dummy;
curr = head;
while (count >= k) {
ListNode newHead = reverseKNodes(curr, k);
prevGroupTail.next = newHead;
prevGroupTail = curr;
curr = curr.next;
count -= k;
}
return dummy.next;
}
private ListNode reverseKNodes(ListNode head, int k) {
ListNode prev = null, curr = head;
while (k > 0) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
k--;
}
head.next = curr;
return prev;
}
}