-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorderList.java
More file actions
94 lines (85 loc) · 1.97 KB
/
ReorderList.java
File metadata and controls
94 lines (85 loc) · 1.97 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
public class ReorderList {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public void reorderList(ListNode head) {
if (head == null) {
return;
}
ListNode firstHalf = half(head);
ListNode newHead = reverseList(firstHalf.next);
firstHalf.next = null;
ListNode firstHead = head;
ListNode secondHead = newHead;
while (firstHead != null && secondHead != null) {
ListNode temp = firstHead.next;
firstHead.next = secondHead;
firstHead = temp;
temp = secondHead.next;
secondHead.next = firstHead;
secondHead = temp;
}
}
public ListNode half(ListNode root) {
if (root == null) {
return root;
}
ListNode slow = root;
ListNode fast = root;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode reverseList(ListNode root) {
if (root == null) {
return root;
}
else if (root.next == null) {
return root;
}
else if (root.next.next == null) {
ListNode newRoot = root.next;
newRoot.next = root;
root.next = null;
return newRoot;
}
ListNode cur = null;
ListNode next = root;
while (next != null) {
ListNode temp = next.next;
next.next = cur;
cur = next;
next = temp;
}
return cur;
}
public void testReverse() {
ListNode root = new ListNode(0);
root.next = new ListNode(1);
root.next.next = new ListNode(2);
root.next.next.next = new ListNode(3);
ListNode newRoot = reverseList(root);
while (newRoot != null) {
System.out.print(newRoot.val + " ");
newRoot = newRoot.next;
}
}
public void testReorder() {
ListNode root = new ListNode(0);
root.next = new ListNode(1);
root.next.next = new ListNode(2);
root.next.next.next = new ListNode(3);
reorderList(root);
while(root != null) {
System.out.print(root.val + " ");
root = root.next;
}
}
}