Skip to content

Commit 0feab81

Browse files
committed
Solution for: Reorder list
1 parent b9dbb14 commit 0feab81

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/leetcode/ReorderList.java

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package leetcode;
2+
3+
public class ReorderList {
4+
public void reorderList(ListNode head) {
5+
if (head == null || head.next == null) {
6+
return;
7+
}
8+
ListNode slow = head;
9+
ListNode fast= head;
10+
while(fast!=null && fast.next!=null){
11+
fast= fast.next.next;
12+
slow= slow.next;
13+
}
14+
15+
ListNode second = slow.next;
16+
slow.next = null;
17+
18+
fast= head;
19+
second= reverse(second);
20+
21+
while (second != null) {
22+
ListNode temp1 = fast.next;
23+
ListNode temp2 = second.next;
24+
fast.next =second;
25+
second.next = temp1;
26+
fast= temp1;
27+
second= temp2;
28+
}
29+
30+
}
31+
32+
public ListNode reverse(ListNode head){
33+
ListNode prev=null;
34+
while(head!=null){
35+
ListNode temp = head.next;
36+
head.next= prev;
37+
prev= head;
38+
head= temp;
39+
}
40+
return prev;
41+
}
42+
}

0 commit comments

Comments
 (0)