-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
32 lines (28 loc) · 833 Bytes
/
Solution.java
File metadata and controls
32 lines (28 loc) · 833 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
if (head == null) return;
LinkedList<ListNode> stack = new LinkedList<ListNode>(),
reversedStack = new LinkedList<ListNode>();
int length = 0;
while (head != null) {
stack.addFirst(head);
reversedStack.addLast(head);
length++;
head = head.next;
}
ListNode p = new ListNode(-1);
for (int i = 0; i < length; i++) {
p.next = i % 2 == 0 ? reversedStack.pop() : stack.pop();
p = p.next;
p.next = null;
}
}
}