-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
52 lines (51 loc) · 1.41 KB
/
Solution.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
/**
* 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 reverseEvenLengthGroups(ListNode head) {
int n = 0;
for (ListNode t = head; t != null; t = t.next) {
++n;
}
ListNode dummy = new ListNode(0, head);
ListNode prev = dummy;
int l = 1;
for (; (1 + l) * l / 2 <= n && prev != null; ++l) {
if (l % 2 == 0) {
ListNode node = prev.next;
prev.next = reverse(node, l);
}
for (int i = 0; i < l && prev != null; ++i) {
prev = prev.next;
}
}
int left = n - l * (l - 1) / 2;
if (left > 0 && left % 2 == 0) {
ListNode node = prev.next;
prev.next = reverse(node, left);
}
return dummy.next;
}
private ListNode reverse(ListNode head, int l) {
ListNode prev = null;
ListNode cur = head;
ListNode tail = cur;
int i = 0;
while (cur != null && i < l) {
ListNode t = cur.next;
cur.next = prev;
prev = cur;
cur = t;
++i;
}
tail.next = cur;
return prev;
}
}