-
Notifications
You must be signed in to change notification settings - Fork 7
/
Main.java
51 lines (42 loc) · 1.1 KB
/
Main.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
package com.company;
import java.util.ArrayList;
import java.util.List;
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public class Main {
public static void main(String[] args) {
ListNode head = generate(new int[]{1, 2, 3, 4, 5});
reorderList(head);
}
public static void reorderList(ListNode head) {
if (head == null) return;
List<ListNode> nodes = new ArrayList<>();
while (head != null) {
nodes.add(head);
head = head.next;
}
int li = 0, hi = nodes.size() - 1;
while (li < hi) {
nodes.get(li++).next = nodes.get(hi);
nodes.get(hi--).next = nodes.get(li);
}
nodes.get(li).next = null;
}
public static ListNode generate(int[] nums) {
ListNode res = null;
for (int i = nums.length - 1; i >= 0; i--)
res = new ListNode(nums[i], res);
return res;
}
}