← Home

92. Reverse Linked List II

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

Let's make this one less mysterious. For 92. Reverse Linked List II, 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:

  • iteration

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are reverseBetween, reverseN.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • 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. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

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), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//iteration
02//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Reverse Linked List II.
03//Memory Usage: 7.8 MB, less than 18.66% of C++ online submissions for Reverse Linked List II.
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    ListNode* reverseBetween(ListNode* head, int m, int n) {
17        if(!head || !head->next) return head;
18        
19        ListNode* dummy = new ListNode(-1);
20        dummy->next = head;
21        ListNode* cur = dummy;
22        ListNode* pre;
23        ListNode *rdummy = new ListNode(-1), *rtail, *rcur;
24        
25        //start from dummy because we need the previous node of reversed list
26        for(int i = 0; cur; ++i){
27            // cout << i << ": " << cur->val << endl;
28            ListNode* next = cur->next;
29            if(i == m-1){
30                //the previous node of reversed list
31                pre = cur;
32            }else if(i >= m && i <= n){
33                if(i == m) rtail = cur;
34                //prepend cur to the head of reversed list
35                cur->next = rdummy->next;
36                rdummy->next = cur;
37                //connect reversed list's tail with the org list
38                if(i == n){
39                    rtail->next = next;
40                    break;
41                }
42            }
43            cur = next;
44        }
45        
46        //connect reversed list's head with the org list
47        pre->next = rdummy->next;
48        
49        return dummy->next;
50    }
51};
52
53//Approach 2: Iterative Link Reversal.
54//Runtime: 4 ms, faster than 64.33% of C++ online submissions for Reverse Linked List II.
55//Memory Usage: 7.9 MB, less than 5.08% of C++ online submissions for Reverse Linked List II.
56//time: O(N), space: O(1)
57class Solution {
58public:
59    ListNode* reverseBetween(ListNode* head, int m, int n) {
60        ListNode *dummy = new ListNode(-1);
61        dummy->next = head;
62        
63        ListNode *prev = dummy, *cur = head;
64        
65        //move cur "m-1" steps forward, so it become the mth node
66        int i = 1;
67        for(; i < m; ++i){
68            prev = prev->next;
69            cur = cur->next;
70        }
71        
72        //rdummy: the previous node of the head of reversed list
73        ListNode *rdummy = prev;
74        //rtail: the tail of reversed list
75        ListNode *rtail = cur;
76        
77        //do n-m+1 times, moving "cur" from mth node to (n+1)th node
78        //m -> (m-1), (m+1) -> m, ..., n->(n-1)
79        for(; i <= n; ++i){
80            ListNode* next = cur->next;
81            cur->next = prev;
82            prev = cur;
83            cur = next;
84        }
85        
86        //prev is the tail of reversed list
87        rdummy->next = prev;
88        //cur is the next node of the tail of reversed list
89        rtail->next = cur;
90        
91        return dummy->next;
92    }
93};
94
95//recursion
96//https://leetcode.com/problems/reverse-linked-list-ii/solution/242639
97//time: O(N)
98//space: O(N), space used by recursion
99//for reverse the whole list, check https://github.com/keineahnung2345/leetcode-cpp-practices/blob/master/206.%20Reverse%20Linked%20List.cpp
100class Solution {
101public:
102    ListNode* successor;
103
104    ListNode* reverseN(ListNode* head, int n){
105        if(n == 1){
106            //successor: the node after the first n nodes
107            successor = head->next;
108            return head;
109        }
110
111        ListNode* rhead = reverseN(head->next, n-1);
112
113        //head is now the new tail of reversed list
114        head->next->next = head;
115        head->next = successor;
116
117        return rhead;
118    }
119    
120    ListNode* reverseBetween(ListNode* head, int m, int n){
121        if(m == 1){
122            return reverseN(head, n);
123        }
124
125        head->next = reverseBetween(head->next, m-1, n-1);
126
127        return head;
128    }
129};

Cost

Complexity

Time
O(N), space: O(1)
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.