Reorder List

描述

Given a singly linked list L:L0L1Ln1LnL: L0 \rightarrow L_1 \rightarrow \cdots \rightarrow L{n-1} \rightarrow Ln,reorder it to: L0LnL1Ln1L2Ln2L_0 \rightarrow L_n \rightarrow L_1 \rightarrow L{n-1} \rightarrow L2 \rightarrow L{n-2} \rightarrow \cdots

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}.

分析

题目规定要in-place,也就是说只能使用O(1)的空间。

可以找到中间节点,断开,把后半截单链表reverse一下,再合并两个单链表。

代码

  1. // Reorder List
  2. // 时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public void reorderList(ListNode head) {
  5. if (head == null || head.next == null) return;
  6. ListNode slow = head, fast = head, prev = null;
  7. while (fast != null && fast.next != null) {
  8. prev = slow;
  9. slow = slow.next;
  10. fast = fast.next.next;
  11. }
  12. prev.next = null; // cut at middle
  13. slow = reverse(slow);
  14. // merge two lists
  15. ListNode curr = head;
  16. while (curr.next != null) {
  17. ListNode tmp = curr.next;
  18. curr.next = slow;
  19. slow = slow.next;
  20. curr.next.next = tmp;
  21. curr = tmp;
  22. }
  23. curr.next = slow;
  24. }
  25. ListNode reverse(ListNode head) {
  26. if (head == null || head.next == null) return head;
  27. ListNode prev = head;
  28. for (ListNode curr = head.next, next = curr.next; curr != null;
  29. prev = curr, curr = next, next = next != null ? next.next : null) {
  30. curr.next = prev;
  31. }
  32. head.next = null;
  33. return prev;
  34. }
  35. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/linear-list/linked-list/reorder-list.html