-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
executable file
·65 lines (59 loc) · 1.7 KB
/
Solution.java
File metadata and controls
executable file
·65 lines (59 loc) · 1.7 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
65
package $025;
import datastruc.ListNode;
/**
* @author Junlan Shuai[shuaijunlan@gmail.com].
* @date Created on 9:02 2018/3/22.
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null){
return head;
}
ListNode node = null, linkNode = null;
boolean tag = true;
while (tag){
ListNode temp = head, tempLength = head;
for (int j = 1; j < k; j++){
tempLength = tempLength.next;
if (tempLength == null){
tag = false;
break;
}
}
if (!tag){
break;
}
for (int i = 1; i < k; i++){
ListNode next = temp.next;
temp.next = next.next;
next.next = head;
head = next;
}
if(linkNode != null){
linkNode.next = head;
}
linkNode = temp;
if (node == null){
node = head;
}
head = temp.next;
if (head == null){
break;
}
}
return node == null ? head : node;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode head1 = new ListNode(2);
ListNode head2 = new ListNode(3);
ListNode head3 = new ListNode(4);
ListNode head4 = new ListNode(5);
head.next = head1;
head1.next = head2;
head2.next = head3;
head3.next = head4;
Solution solution = new Solution();
solution.reverseKGroup(head, 1);
}
}