forked from shenzhu/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path143. Reorder List.java
More file actions
53 lines (45 loc) · 1.28 KB
/
143. Reorder List.java
File metadata and controls
53 lines (45 loc) · 1.28 KB
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null) return;
// Find the middle of the list
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
// Reverse last half of linked list
slow.next = reverseList(slow.next);
// Reorder one by one
ListNode p1 = head;
ListNode p2 = slow.next;
//while(p1 != slow){
while(p1 != null && p2 != null){
slow.next = p2.next;
p2.next = p1.next;
p1.next = p2;
p1 = p1.next.next;
p2 = slow.next;
}
}
private ListNode reverseList(ListNode head){
ListNode prev = null;
ListNode curr = head;
ListNode next = null;
while(curr != null){
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}