-
Notifications
You must be signed in to change notification settings - Fork 4
/
143. Reorder List
35 lines (34 loc) · 1021 Bytes
/
143. Reorder List
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
//O(n) time and O(1) space
class Solution {
public void reorderList(ListNode head) {
if(head==null || head.next==null) return;
ListNode slow = head, fast = head;
while(fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
}
if(fast!=null) slow = slow.next;
ListNode l1 = head;
ListNode l2 = reverse(slow);
ListNode h1 = l1, h2 = l2;
while(l1!=null && l2!=null && !l1.equals(h2)){
ListNode fnext = l1.next, snext = l2.next;
l1.next = l2;
l2.next = fnext;
l1 = fnext;
l2 = snext;
}
l1.next = l2;
}
public ListNode reverse(ListNode head){
if(head==null || head.next==null) return head;
ListNode cur = head, prev = null;
while(cur!=null){
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
}