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}
.
分析:先用快慢指针找到链表的中点,然后翻转链表后半部分,再和前半部分组合。需要注意的是把链表分成两半时,前半段的尾节点要置为NULL,翻转链表时也要把尾节点置为NULL。
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 // IMPORTANT: Please reset any member data you declared, as 15 // the same Solution instance will be reused for each test case. 16 if(head == null || head.next == null) return; 17 ListNode fast = head, slow = head; 18 while(fast != null && fast.next != null){ 19 fast = fast.next.next; 20 slow = slow.next; 21 } 22 fast = slow.next; 23 slow.next = null; 24 fast = reverse(fast); 25 while(head != null && fast != null){//merge 26 ListNode tmp1 = head.next; 27 ListNode tmp2 = fast.next; 28 head.next = fast; 29 fast.next = tmp1; 30 head = tmp1; 31 fast = tmp2; 32 } 33 } 34 ListNode reverse(ListNode root){ 35 ListNode first = null, second = root; 36 while(second != null){ 37 ListNode tmp = second.next; 38 second.next = first; 39 first = second; 40 second = tmp; 41 } 42 return first; 43 } 44 }
posted on 2013-12-05 05:22 Step-BY-Step 阅读(239) 评论(0) 编辑 收藏 举报