Reorder List

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

 

 1 public class Solution {
 2     public void reorderList(ListNode head) {
 3         if(head==null) return;
 4         ListNode fast = head,slow =head;
 5         while(true){
 6             fast = fast.next;
 7             if(fast==null) break;
 8             fast = fast.next;
 9             if(fast==null) break;
10             slow =slow.next;
11         }
12         
13         ListNode newHead = reverse(slow.next);
14         slow.next = null;
15         merge(head,newHead);
16     }
17     public ListNode reverse(ListNode root){
18         if(root==null) return root;
19         ListNode safe = new ListNode(-1);
20         safe.next = root;
21         ListNode pre = safe,cur = root;
22         while(cur!=null){
23             ListNode temp = cur.next;
24             cur.next = pre;
25             pre = cur;
26             cur = temp;
27         }
28         safe.next.next = null;
29         safe.next = pre;
30         return safe.next;
31     }
32     public void merge(ListNode l1,ListNode l2){
33         while(l1!=null && l2!=null){
34             ListNode temp = l1.next;
35             l1.next = l2;
36             ListNode temp2 = l2.next;
37             l2.next = temp;
38             l2 = temp2;
39             l1 = temp;
40         }
41     }
42 }
View Code

 

 

 

 1 public class Solution {
 2     public void reorderList(ListNode head) {
 3         if(head==null) return ;
 4         ListNode fast = head, slow = head;
 5         while(true){
 6             fast = fast.next;
 7             if(fast==null) break;
 8             fast = fast.next;
 9             if(fast==null) break;
10             slow = slow.next;
11         }
12         if(slow==null) return;
13         ListNode cur = slow;
14         ListNode pre = cur.next;
15         cur.next = null;
16         while(pre!=null){
17             ListNode temp = pre.next;
18             pre.next = cur;
19             cur = pre;
20             pre = temp;
21         }
22         ListNode f = head, s = cur;
23         while(f!=null && s!=null && f!=s){
24             ListNode temp = s.next;
25             s.next = f.next;
26             f.next = s;
27             f = s.next;
28             s = temp;
29         }
30     }
31 }
View Code

 

posted @ 2014-02-22 16:23  krunning  阅读(251)  评论(0编辑  收藏  举报