-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorderList.java
More file actions
42 lines (37 loc) · 1 KB
/
Copy pathReorderList.java
File metadata and controls
42 lines (37 loc) · 1 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
import java.util.Stack;
/**
* 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 void reorderList(ListNode head) {
if (head == null || head.next == null)
return;
Stack<ListNode> stack = new Stack<>();
ListNode dummy = head;
while (dummy != null) {
stack.push(dummy);
dummy = dummy.next;
}
int size = stack.size();
for (int i = 0; i < size / 2; i++) {
ListNode temp = stack.pop();
ListNode next = head.next;
head.next = temp;
temp.next = next;
head = next;
}
if (size % 2 == 0) {
head.next = null;
} else {
head.next = stack.pop();
head.next.next = null;
}
}
}