-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorderList.java
More file actions
45 lines (32 loc) · 930 Bytes
/
Copy pathReorderList.java
File metadata and controls
45 lines (32 loc) · 930 Bytes
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
package org.example;
import java.util.ArrayList;
import java.util.List;
public class ReorderList {
public void reorderList(ListNode head) {
ListNode p = head;
// 这里是用ArrayList,还是用LinkedList
List<ListNode> list = new ArrayList<>();
while (p != null) {
list.add(p);
p = p.next;
}
ListNode dummy = new ListNode();
dummy.next = head;
ListNode pre = dummy;
int n = list.size();
for (int i = 0; i < n / 2; i++) {
ListNode first = list.get(i);
ListNode second = list.get(n - 1 - i);
pre.next = first;
first.next = second;
second.next = null;
pre = second;
}
if (n % 2 == 1) {
pre.next = list.get(n / 2);
pre = pre.next;
}
pre.next = null;
head = dummy.next;
}
}