Skip to content

Commit 0a100db

Browse files
authored
Create Reorder_List.java
1 parent 3b45fda commit 0a100db

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

LeetCode/Reorder_List.java

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
3+
find the question here - https://leetcode.com/problems/reorder-list/
4+
5+
6+
* Definition for singly-linked list.
7+
* public class ListNode {
8+
* int val;
9+
* ListNode next;
10+
* ListNode() {}
11+
* ListNode(int val) { this.val = val; }
12+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
13+
* }
14+
15+
16+
Step 1: find the mid point
17+
while(pt2.next!=null && pt2.next.next!=null){
18+
pt1=pt1.next;
19+
pt2=pt2.next.next
20+
21+
Step 2: Reverse the end of the list
22+
23+
Reverse the half after middle 1->2->3->4->5->6 to 1->2->3->6->5->4
24+
25+
Step 3: merge both the list by reordering them one by one in order
26+
27+
reorder one by one 1->2->3->6->5->4 to 1->6->2->5->3->4
28+
*/
29+
30+
class Solution {
31+
32+
public void reorderList(ListNode head) {
33+
if(head==null||head.next==null) return;
34+
35+
//Find the middle of the list
36+
ListNode pt1=head;
37+
ListNode pt2=head;
38+
while(pt2.next!=null && pt2.next.next!=null){
39+
pt1=pt1.next;
40+
pt2=pt2.next.next;
41+
}
42+
43+
//Reverse the half after middle 1->2->3->4->5->6 to 1->2->3->6->5->4
44+
ListNode preMid=pt1;
45+
ListNode preCurr=pt1.next;
46+
while(preCurr.next!=null){
47+
ListNode curr=preCurr.next;
48+
preCurr.next=curr.next;
49+
curr.next=preMid.next;
50+
preMid.next=curr;
51+
}
52+
53+
//Start reorder one by one 1->2->3->6->5->4 to 1->6->2->5->3->4
54+
pt1=head;
55+
pt2=preMid.next;
56+
while(pt1!=preMid){
57+
preMid.next=pt2.next;
58+
pt2.next=pt1.next;
59+
pt1.next=pt2;
60+
pt1=pt2.next;
61+
pt2=preMid.next;
62+
}
63+
}
64+
}

0 commit comments

Comments
 (0)