-
Notifications
You must be signed in to change notification settings - Fork 1
/
ReorderList.java
42 lines (36 loc) · 904 Bytes
/
ReorderList.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
package leetcode;
public class ReorderList {
public void reorderList(ListNode head) {
if (head == null || head.next == null) {
return;
}
ListNode slow = head;
ListNode fast= head;
while(fast!=null && fast.next!=null){
fast= fast.next.next;
slow= slow.next;
}
ListNode second = slow.next;
slow.next = null;
fast= head;
second= reverse(second);
while (second != null) {
ListNode temp1 = fast.next;
ListNode temp2 = second.next;
fast.next =second;
second.next = temp1;
fast= temp1;
second= temp2;
}
}
public ListNode reverse(ListNode head){
ListNode prev=null;
while(head!=null){
ListNode temp = head.next;
head.next= prev;
prev= head;
head= temp;
}
return prev;
}
}