Cover image for LeetCode Hot 100 P206 Reverse Linked List

LeetCode Hot 100 P206 Reverse Linked List

Words 278
Views
Visitors

Timeline

Timeline

2026-03-13

init

linked list

Problem:

Use a stack to store all nodes of the linked list, then popping them out gives the reversed linked list.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
struct ListNode {        int val;        ListNode *next;        ListNode()                : val(0)                , next(nullptr)        {        }        ListNode(int x)                : val(x)                , next(nullptr)        {        }        ListNode(int x, ListNode *next)                : val(x)                , next(next)        {        }};#include <stack>using std::stack;class Solution {    public:        ListNode *reverseList(ListNode *head)        {                if (head == nullptr)                        return nullptr;                                ListNode *p = head;                stack<ListNode *> stk;                while (p != nullptr) {                        stk.push(p);                        p = p->next;                }                head = stk.top();                ListNode *last = head;                stk.pop();                while (!stk.empty()) {                        p = stk.top();                        stk.pop();                        last->next = p;                        last = p;                }                last->next = nullptr;                return head;        }};

After reading the solution, it can also be done with only O(1) space complexity.

Suppose the linked list is 1→2→3→∅, we want to change it to ∅←1←2←3.

While traversing the linked list, change the current node’s next pointer to point to the previous node. Since a node does not have a reference to its previous node, you must store its previous node in advance. Before changing the reference, you also need to store the next node. Finally, return the new head reference.

123456789101112131415
class Solution {public:    ListNode* reverseList(ListNode* head) {        ListNode* prev = nullptr;        ListNode* curr = head;        while (curr) {            ListNode* next = curr->next;            curr->next = prev;            prev = curr;            curr = next;        }        return prev;    }};
Loading comments…