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 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public void reorderList(ListNode head) {
11     
12     try{
13         if(head.next.next!=null){
14              ListNode p=head;
15              
16              Map<ListNode,ListNode> map=new HashMap<>();
17              
18             while(p.next.next!=null)
19             {
20                 map.put(p.next,p);
21                 p=p.next;
22             }
23              ListNode q=head;
24              ListNode temp=p.next;
25       
26              
27              while(q.next!=p.next&&q.next!=null)
28              {
29                  p.next=temp.next;
30                  temp.next=q.next;
31                  q.next=temp;
32                  q=temp.next;
33                  
34                  temp=p;
35                  p=map.get(p);
36              }
37              
38         }
39         
40     }catch(NullPointerException e){}
41        
42     }
43 }