LeetCode-Reorder List

Given a singly linked list L: L0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.

Solution:

 1 /**
 2  * Definition for singly-linked list.
 3  * class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public void reorderList(ListNode head) {
14         if (head==null || head.next==null) return;
15         ListNode preHead = new ListNode(0);
16         preHead.next = head;
17         //Find the median node.
18         ListNode p1 = preHead, p2 = preHead;
19         while (p2!=null && p2.next!=null){
20             p1 = p1.next;
21             p2 = p2.next.next;
22         }
23         
24         //Reverse the list after p1.
25         p2 = p1.next;
26         while (p2.next!=null){
27             ListNode temp = p2.next.next;
28             p2.next.next = p1.next;
29             p1.next = p2.next;
30             p2.next = temp;
31         }
32 
33         //Insert the list after p1 into the list before p1.
34         p2 = p1.next;
35         p1.next = null;
36         p1 = head;
37         while (p1!=null && p2!=null){
38             ListNode temp = p2.next;
39             p2.next = p1.next;
40             p1.next = p2;
41             p1 = p1.next.next;
42             p2 = temp;
43         }
44         
45         
46     }
47 }

 

你可能感兴趣的:(LeetCode-Reorder List)