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:
  5. void reorderList(ListNode *head) {
  6. if (head == nullptr || head->next == nullptr) return;
  7. ListNode *slow = head, *fast = head, *prev = nullptr;
  8. while (fast && fast->next) {
  9. prev = slow;
  10. slow = slow->next;
  11. fast = fast->next->next;
  12. }
  13. prev->next = nullptr; // cut at middle
  14. slow = reverse(slow);
  15. // merge two lists
  16. ListNode *curr = head;
  17. while (curr->next) {
  18. ListNode *tmp = curr->next;
  19. curr->next = slow;
  20. slow = slow->next;
  21. curr->next->next = tmp;
  22. curr = tmp;
  23. }
  24. curr->next = slow;
  25. }
  26. ListNode* reverse(ListNode *head) {
  27. if (head == nullptr || head->next == nullptr) return head;
  28. ListNode *prev = head;
  29. for (ListNode *curr = head->next, *next = curr->next; curr;
  30. prev = curr, curr = next, next = next ? next->next : nullptr) {
  31. curr->next = prev;
  32. }
  33. head->next = nullptr;
  34. return prev;
  35. }
  36. };

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