← Home

143. Reorder List

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
143

The trick here is to name the state correctly, then let the implementation follow. For 143. Reorder List, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • https://leetcode.com/problems/reorder-list/discuss/44992/Java-solution-with-3-steps

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are reorderList.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//https://leetcode.com/problems/reorder-list/discuss/44992/Java-solution-with-3-steps
02//Runtime: 40 ms, faster than 72.72% of C++ online submissions for Reorder List.
03//Memory Usage: 14.2 MB, less than 74.29% of C++ online submissions for Reorder List.
04/**
05 * Definition for singly-linked list.
06 * struct ListNode {
07 *     int val;
08 *     ListNode *next;
09 *     ListNode() : val(0), next(nullptr) {}
10 *     ListNode(int x) : val(x), next(nullptr) {}
11 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
12 * };
13 */
14class Solution {
15public:
16    void reorderList(ListNode* head) {
17        //0 or 1 valid node
18        if(!head || !head->next)
19            return;
20        
21        //find the middle point
22        /*
23        for 1->2->3->4->5, now
24        p1 points to 3, p2 points to 5
25        for 1->2->3->4->5->6, now
26        p1 points to 3, p2 points to 5
27        */
28        ListNode *p1 = head, *p2 = head;
29        
30        while(p2->next && p2->next->next){
31            p1 = p1->next;
32            p2 = p2->next->next;
33        }
34        
35        //reverse the later half
36        /*
37        for 1->2->3->4->5, now
38        1->2->3->5->4
39        for 1->2->3->4->5->6, now
40        1->2->3->6->5->4
41        */
42        ListNode *preMid = p1, *preCur = p1->next;
43        while(preCur->next){
44            ListNode* cur = preCur->next;
45            // cout << "preCur->(cur->next): " << preCur->val << "->" << (cur->next ? cur->next->val : -1) <<endl;
46            // cout << "cur->(preMid->next): " << cur->val << "->" << preMid->next->val << endl;
47            // cout << "preMid->cur: " << preMid->val << "->" << cur->val << endl;
48            
49            /*
50            at first iteration, cur is the 2nd node of later part
51            in each iteration, 
52            we move cur so it becomes the new head of later part
53            in the loop, cur is 2nd node, then 3rd node, then 4th, ...
54            */
55            preCur->next = cur->next;
56            cur->next = preMid->next;
57            /*
58            preMid serves as the previous node of later part,
59            it will not be changed it this step
60            preMid->next points to the head of later part
61            */
62            preMid->next = cur;
63        }
64        // cout << endl;
65        
66        //start reorder
67        /*
68        for 1->2->3->4->5,
69        it becomes 1->2->3->5->4
70        and then 1->5->2->4->3
71        for 1->2->3->4->5->6,
72        it becomes 1->2->3->6->5->4
73        and then 1->6->2->3->5->4
74        and then 1->6->2->5->3->4
75        */
76        p1 = head;
77        p2 = preMid->next;
78        
79        while(p1 != preMid){
80            /*
81            p2 is the head of later part
82            in each iteration, 
83            move p2 to the behind of p1
84            (p1 is initially the head of former part,
85            but it will move)
86            */
87            // cout << "premid->(p2->next): " << preMid->val << "->" << (p2->next ? p2->next->val : -1) << endl;
88            // cout << "p2->(p1->next): " << p2->val << "->" << p1->next->val << endl;
89            // cout << "p1->p2: " << p1->val << "->" << p2->val << endl;
90            preMid->next = p2->next;
91            p2->next = p1->next;
92            p1->next = p2;
93            p1 = p2->next;
94            p2 = preMid->next;
95        }
96    }
97};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.