-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path25.reverse-nodes-in-k-group.java
90 lines (77 loc) · 2.03 KB
/
25.reverse-nodes-in-k-group.java
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
81
82
83
84
85
86
87
88
89
/*
* @lc app=leetcode id=25 lang=java
*
* [25] Reverse Nodes in k-Group
*/
// @lc code=start
/**
* 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) {
if (k == 1) {
return head;
}
ListNode curr = head;
ListNode indexNode = head;
ListNode tail = null;
ListNode result = new ListNode(-1);
ListNode reverseList = null;
int count = 1;
while (indexNode != null && indexNode.next != null) {
count++;
indexNode = indexNode.next;
if (count == k) {
//save the tail
tail = indexNode.next;
//cut the tail
indexNode.next = null;
//reverse the previous group
reverseList = reverse(curr);
//reset
curr = tail;
indexNode = tail;
count = 1;
}
if (reverseList != null) {
result = LinkNode(result, reverseList);
reverseList = null;
}
}
result = LinkNode(result, tail);
return result.next;
}
public ListNode LinkNode(ListNode l1, ListNode l2) {
if (l2 == null) {
return l1;
}
ListNode head = l1;
while (l1.next != null) {
l1 = l1.next;
}
l1.next = l2;
return head;
}
public ListNode reverse(ListNode head) {
if (head == null) {
return head;
}
ListNode pre = null;
ListNode curr = head;
while (curr != null) {
ListNode temp = curr.next;
curr.next = pre;
pre = curr;
curr = temp;
}
return pre;
}
}
// @lc code=end