Skip to content

Commit 1c38372

Browse files
authored
Create 25. Reverse Nodes in k-Group
1 parent f8974c9 commit 1c38372

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

25. Reverse Nodes in k-Group

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode reverseKGroup(ListNode head, int k) {
13+
int count =0;
14+
ListNode dummy = new ListNode();
15+
dummy.next = head;
16+
17+
ListNode temp = dummy;
18+
19+
while(temp.next!=null){
20+
temp = temp.next;
21+
count++;
22+
}
23+
temp = dummy;
24+
while(temp.next!=null){
25+
if(count<k) break;
26+
int nodes = k-1;
27+
ListNode tempnext = temp.next;
28+
ListNode first = temp.next;
29+
ListNode second = first.next;
30+
31+
while(nodes-- > 0){
32+
ListNode next = second.next;
33+
second.next = first;
34+
first = second;
35+
second = next;
36+
}
37+
count-=k;
38+
temp.next = first;
39+
tempnext.next = second;
40+
temp = tempnext;
41+
42+
}
43+
return dummy.next;
44+
}
45+
}

0 commit comments

Comments
 (0)