-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathReorder_List.java
64 lines (50 loc) · 1.8 KB
/
Reorder_List.java
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
find the question here - https://leetcode.com/problems/reorder-list/
* 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; }
* }
Step 1: find the mid point
while(pt2.next!=null && pt2.next.next!=null){
pt1=pt1.next;
pt2=pt2.next.next
Step 2: Reverse the end of the list
Reverse the half after middle 1->2->3->4->5->6 to 1->2->3->6->5->4
Step 3: merge both the list by reordering them one by one in order
reorder one by one 1->2->3->6->5->4 to 1->6->2->5->3->4
*/
class Solution {
public void reorderList(ListNode head) {
if(head==null||head.next==null) return;
//Find the middle of the list
ListNode pt1=head;
ListNode pt2=head;
while(pt2.next!=null && pt2.next.next!=null){
pt1=pt1.next;
pt2=pt2.next.next;
}
//Reverse the half after middle 1->2->3->4->5->6 to 1->2->3->6->5->4
ListNode preMid=pt1;
ListNode preCurr=pt1.next;
while(preCurr.next!=null){
ListNode curr=preCurr.next;
preCurr.next=curr.next;
curr.next=preMid.next;
preMid.next=curr;
}
//Start reorder one by one 1->2->3->6->5->4 to 1->6->2->5->3->4
pt1=head;
pt2=preMid.next;
while(pt1!=preMid){
preMid.next=pt2.next;
pt2.next=pt1.next;
pt1.next=pt2;
pt1=pt2.next;
pt2=preMid.next;
}
}
}