-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path25. Reverse Nodes in k-Group
45 lines (41 loc) · 1.16 KB
/
25. Reverse Nodes in k-Group
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
/**
* 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 {
public ListNode reverseKGroup(ListNode head, int k) {
int count =0;
ListNode dummy = new ListNode();
dummy.next = head;
ListNode temp = dummy;
while(temp.next!=null){
temp = temp.next;
count++;
}
temp = dummy;
while(temp.next!=null){
if(count<k) break;
int nodes = k-1;
ListNode tempnext = temp.next;
ListNode first = temp.next;
ListNode second = first.next;
while(nodes-- > 0){
ListNode next = second.next;
second.next = first;
first = second;
second = next;
}
count-=k;
temp.next = first;
tempnext.next = second;
temp = tempnext;
}
return dummy.next;
}
}