Skip to content

Commit 1152216

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

File tree

1 file changed

+37
-37
lines changed

1 file changed

+37
-37
lines changed

src/leetcode/ReorderList.java

+37-37
Original file line numberDiff line numberDiff line change
@@ -2,41 +2,41 @@
22

33
public class ReorderList {
44
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-
}
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+
}
4242
}

0 commit comments

Comments
 (0)