-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathReverseNodeInKGroup.java
More file actions
54 lines (47 loc) · 964 Bytes
/
ReverseNodeInKGroup.java
File metadata and controls
54 lines (47 loc) · 964 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
// Start typing your Java solution below
// DO NOT write main() function
if(head==null || head.next == null) return head;
if(k == 1) return head;
ListNode p = new ListNode(-1);
p.next = head;
head = p;
ListNode q = p.next;
ListNode r = q;
ListNode s;
while(r!= null){
r = q;
for(int i= 1; i<k; i++){
if(r==null)
break;
else
r =r.next;
}
if(r==null) break;
s = r.next;
reverse(q,r);
p.next = r;
q.next = s;
p = q;
q = s;
}
return head.next;
}
public void reverse(ListNode p, ListNode q){
if(p.next != q)
reverse(p.next, q);
p.next.next = p;
}
}