LeetCode K个一组链表翻转

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class ListNode{
private int val;
private ListNode next;

public ListNode(){}

public ListNode(int val){
this.val = val;
}

public ListNode(int val,ListNode node){
this.val= val;
this.next = node;
}



}

class Solution{


public ListNode getKreverseNode(ListNode node,int k){

ListNode dump = new ListNode(0);
dump.next = node;

ListNode pre = dump;
// ListNode start = dump;
ListNode end = dump;

while(end.next != null){
for(int i=0;i< k&& end != null;i++){
end = end.next;
}

if(end == null){
break;
}
ListNode start = pre.next;
ListNode next = end.next;

end.next = null;
ListNode reverseNode = reverse(start);
pre.next= reverseNode;
// end.next 接回去
start.next= next;


// 更新指针 //重置start的起始位置开始下一轮的转换
pre = start;
end = pre;


}
return dump.next;



}

// 链表反转
public ListNode reverse(ListNode node){
ListNode pre =null;
ListNode cur = node;
while(cur != null){
ListNode next = cur.next;
cur.next= pre;
pre = cur;
cur = next;
}
return pre;


}


}


__END__