Skip to content

Commit 0f78ecd

Browse files
committed
Reorder List
1 parent 4a85b9e commit 0f78ecd

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

reorder-list/TonyKim9401.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// TC: O(n)
2+
// -> find middle, reverse, merge -> max O(n)
3+
// SC: O(1)
4+
class Solution {
5+
public void reorderList(ListNode head) {
6+
if (head == null || head.next == null) return;
7+
8+
ListNode slow = head, fast = head;
9+
while (fast != null && fast.next != null) {
10+
slow = slow.next;
11+
fast = fast.next.next;
12+
}
13+
14+
ListNode backSide = null;
15+
ListNode curr = slow.next;
16+
slow.next = null;
17+
18+
while (curr != null) {
19+
ListNode temp = curr.next;
20+
curr.next = backSide;
21+
backSide = curr;
22+
curr = temp;
23+
}
24+
25+
ListNode first = head;
26+
ListNode second = backSide;
27+
while (second != null) {
28+
ListNode temp = first.next;
29+
first.next = second;
30+
first = second;
31+
second = temp;
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)