143. Reorder List
Given a singly linked list L: L0?L1?…?Ln-1?Ln,
reorder it to: L0?Ln?L1?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}
.
分3步:
1.快慢指针找到中点(1-2-3-4-5-6)
2 反转后半部分(1-2-3-6-5-4)
3.merge (1-6-2-5-4-3-4)
1 class Solution { 2 public void reorderList(ListNode head) { 3 if(head !=null){ 4 ListNode slower = head; 5 ListNode faster = head; 6 while(faster != null && faster.next != null){ 7 faster = faster.next.next; 8 slower = slower.next; 9 } 10 ListNode p2 = reverseList(slower); 11 ListNode p1 = head; 12 while(p2.next!=null){ 13 ListNode p1_next = p1.next; 14 ListNode p2_next = p2.next; 15 p2.next = p1.next; 16 p1.next = p2; 17 p2 = p2_next; 18 p1 =p1_next; 19 } 20 } 21 22 23 } 24 public ListNode reverseList(ListNode head) { 25 if(head == null ||head.next == null) return head; 26 ListNode pre = head; 27 head = head.next; 28 pre.next = null; 29 while(head != null){ 30 ListNode next = head.next; 31 head.next = pre; 32 pre = head; 33 head = next; 34 } 35 return pre; 36 } 37 }