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 → …
Example
Given 1->2->3->4->null
, reorder it to 1->4->2->3->null
.
分析:
先得到后一半,然后reverse后一半,再和前一半合并。
1 /** 2 * Definition for ListNode. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int val) { 7 * this.val = val; 8 * this.next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @param head: The head of linked list. 15 * @return: void 16 */ 17 public void reorderList(ListNode head) { 18 if (head == null || head.next == null) return; 19 20 ListNode slow = head; 21 ListNode quick = head; 22 23 while (quick.next != null && quick.next.next != null) { 24 slow = slow.next; 25 quick = quick.next.next; 26 } 27 28 ListNode secondHead = slow.next; 29 slow.next = null; 30 secondHead = reverse(secondHead); 31 32 ListNode firstHead = head; 33 34 while (secondHead != null) { 35 ListNode next1 = firstHead.next; 36 ListNode next2 = secondHead.next; 37 firstHead.next = secondHead; 38 secondHead.next = next1; 39 firstHead = next1; 40 secondHead = next2; 41 } 42 } 43 44 public ListNode reverse(ListNode head) { 45 if (head == null || head.next == null) return head; 46 ListNode pre = head; 47 ListNode cur = head.next; 48 pre.next = null; 49 50 while (cur != null) { 51 ListNode next = cur.next; 52 cur.next = pre; 53 pre = cur; 54 cur = next; 55 } 56 return pre; 57 } 58 }
转载请注明出处:cnblogs.com/beiyeqingteng/