forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreversenodesinkgroup.java
More file actions
executable file
·64 lines (59 loc) · 1.53 KB
/
reversenodesinkgroup.java
File metadata and controls
executable file
·64 lines (59 loc) · 1.53 KB
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
61
62
63
64
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
class Bundle {
public ListNode beg;
public ListNode end;
Bundle(ListNode beg, ListNode end){
this.beg = beg;
this.end = end;
}
}
private Bundle reverseBet(Bundle b){
if(b.beg==b.end) return b;
ListNode pPre = null;
ListNode p = b.beg;
ListNode tmp;
while(p!=b.end){
tmp = p.next;
p.next = pPre;
pPre = p;
p = tmp;
}
p.next = pPre;
return new Bundle(b.end,b.beg);
}
public ListNode reverseKGroup(ListNode head, int k) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode ans = head;
ListNode p = head;
ListNode pPre = new ListNode(0);
pPre.next = head;
Bundle lastBundle = new Bundle(pPre,pPre);
int no = 0;
while(p!=null){
no++;
if(no==k){
no=0;
ListNode pnext = p.next;
Bundle kb = reverseBet(new Bundle(lastBundle.end.next,p));
lastBundle.end.next = kb.beg;
kb.end.next = pnext;
lastBundle = kb;
p = kb.end;
}
p = p.next;
}
return pPre.next;
}
}