Skip to content

Commit 7635c4f

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 143_Reorder_List.java
1 parent fee07e9 commit 7635c4f

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
public void reorderList(ListNode head) {
3+
if (head == null) {
4+
return;
5+
}
6+
7+
ListNode slow = head, fast = head;
8+
9+
while (fast.next != null && fast.next.next != null) {
10+
slow = slow.next;
11+
fast = fast.next.next;
12+
}
13+
14+
ListNode head2 = reverse(slow.next);
15+
slow.next = null;
16+
17+
while (head != null && head2 != null) {
18+
ListNode t1 = head.next;
19+
ListNode t2 = head2.next;
20+
21+
head.next = head2;
22+
head2.next = t1;
23+
24+
head = t1;
25+
head2 = t2;
26+
}
27+
}
28+
29+
private ListNode reverse(ListNode head) {
30+
ListNode prev = null, curr = head;
31+
32+
while (curr != null) {
33+
ListNode tmp = curr.next;
34+
curr.next = prev;
35+
prev = curr;
36+
curr = tmp;
37+
}
38+
39+
return prev;
40+
}
41+
}

0 commit comments

Comments
 (0)