@@ -2598,3 +2598,75 @@ \subsubsection{相关题目}
25982598\begindot
25992599\item Linked List Cycle, 见 \S \ref {sec:Linked-List-Cycle }
26002600\myenddot
2601+
2602+
2603+ \subsection {Reorder List }
2604+ \label {sec:Reorder-List }
2605+
2606+
2607+ \subsubsection {描述 }
2608+ Given a singly linked list $ L: L_0 \rightarrow L_1 \rightarrow \cdots \rightarrow L_{n-1} \rightarrow L_n$ ,
2609+ reorder it to: $ L_0 \rightarrow L_n \rightarrow L_1 \rightarrow L_{n-1} \rightarrow L_2 \rightarrow L_{n-2} \rightarrow \cdots $
2610+
2611+ You must do this in-place without altering the nodes' values.
2612+
2613+ For example,
2614+ Given \fn {\{ 1,2,3,4\} }, reorder it to \fn {\{ 1,4,2,3\} }.
2615+
2616+
2617+ \subsubsection {分析 }
2618+ 题目规定要in-place,也就是说只能使用$ O(1 )$ 的空间。
2619+
2620+ 可以找到中间节点,断开,把后半截单链表reverse一下,再合并两个单链表。
2621+
2622+
2623+ \subsubsection {代码 }
2624+ \begin {Code }
2625+ // LeetCode, Reorder List
2626+ // 时间复杂度O(n),空间复杂度O(1)
2627+ class Solution {
2628+ public:
2629+ void reorderList(ListNode *head) {
2630+ if (head == nullptr || head->next == nullptr) return;
2631+
2632+ ListNode *slow = head, *fast = head, *prev = nullptr;
2633+ while (fast && fast->next) {
2634+ prev = slow;
2635+ slow = slow->next;
2636+ fast = fast->next->next;
2637+ }
2638+ prev->next = nullptr; // cut at middle
2639+
2640+ slow = reverse(slow);
2641+
2642+ // merge two lists
2643+ ListNode *curr = head;
2644+ while (curr->next) {
2645+ ListNode *tmp = curr->next;
2646+ curr->next = slow;
2647+ slow = slow->next;
2648+ curr->next->next = tmp;
2649+ curr = tmp;
2650+ }
2651+ curr->next = slow;
2652+ }
2653+
2654+ ListNode* reverse(ListNode *head) {
2655+ if (head == nullptr || head->next == nullptr) return head;
2656+
2657+ ListNode *prev = head;
2658+ for (ListNode *curr = head->next, *next = curr->next; curr;
2659+ prev = curr, curr = next, next = next ? next->next : nullptr) {
2660+ curr->next = prev;
2661+ }
2662+ head->next = nullptr;
2663+ return prev;
2664+ }
2665+ };
2666+ \end {Code }
2667+
2668+
2669+ \subsubsection {相关题目 }
2670+ \begindot
2671+ \item 无
2672+ \myenddot
0 commit comments