Problem 206

Abstract / Summary

Reverse the order of nodes in a singly linked list and return the new head.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0206.cpp

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (!head)
            return nullptr;

        ListNode* prev = head;
        ListNode* current = head->next;
        head->next = nullptr;
        while (current)
        {
            auto next = current->next;
            current->next = prev;
            prev = current;
            current = next;
        }

        return prev;
    }
};
20 lines | 442 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 81% (8+ million submissions).

Typical patterns to solve this problem:
  • Linked List
  • Recursion
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method to reverse a singly-linked list in place. It receives a pointer to the head node and returns a pointer to the new head after the reversal. The algorithm works iteratively, re-linking each node to its predecessor while traversing the list exactly once.

Key Steps

The first logical branch checks whether the input list is empty. If the head pointer is null, the function immediately returns a null pointer, indicating that there is nothing to reverse.

if (!head)
    return nullptr;

After confirming that the list contains at least one node, two pointers are established. The prev pointer is initialized to the original head node, and the current pointer is set to the node that follows the head. The original head’s next field is cleared to become the tail of the reversed list.

ListNode* prev = head;
ListNode* current = head->next;
head->next = nullptr;

The core of the algorithm is a while loop that continues as long as current is not null. Inside the loop, the next node is saved, the current node’s next field is redirected to point to prev, and then both prev and current advance one step forward. This sequence effectively flips the direction of each link.

while (current)
{
    auto next = current->next;
    current->next = prev;
    prev = current;
    current = next;
}

When the loop terminates, prev points to the node that was originally the last element of the list, which is now the new head. The function returns this pointer.

return prev;

Edge Cases Handled

The implementation explicitly handles the scenario where the input list is empty. By checking if (!head) at the outset, it avoids dereferencing a null pointer and returns a null result, which correctly represents an empty reversed list.

Another implicit edge case is a list consisting of a single node. In this situation, current is initialized to head->next, which is null. The while loop is skipped, and the function returns prev, which still points to the original (and only) node. The node’s next field has already been set to null, preserving the correct single-node structure.

Performance Optimizations

The algorithm operates in a single pass over the list, performing a constant amount of work for each node. By reusing existing node objects and only adjusting pointer fields, it avoids any additional memory allocation. The use of a local auto variable to store the next node (next) ensures that the original forward link is preserved before it is overwritten, eliminating the need for extra data structures.

Because the reversal is performed iteratively rather than recursively, the implementation avoids the overhead of function call stacks and the risk of stack overflow on very long lists. The straightforward pointer manipulation yields minimal instruction count per iteration, contributing to efficient execution on typical processor pipelines.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long train made of several colorful toy cars connected by little hooks. Each car is holding onto the one behind it, creating a line that goes in one direction. The goal here is to turn the whole train around so that the last car becomes the first car, and every car points to the one that was in front of it before.

First, the code checks if the train is empty. If there are no cars at all, there is nothing to flip around.

If there are cars, the code picks up the first car and detaches its hook so it does not point to anything anymore. This car will eventually be the very last car in the new line.

Then, the code starts a loop to move through every single car one by one. For each car, it carefully unhooks it from the car behind it and turns it around to point to the car that was right in front of it. It keeps doing this over and over again, moving down the line, until every car has been turned to face the opposite way.

By the time the loop reaches the end, all the hooks are pointing in the new direction. The last car in the original line is now at the very front of the new train, holding everything together in its new order.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8.5 | μ = 8.42 | σ = 0.84

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust JS Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong C++
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong C++
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
65 links | 48 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'K Reverse in Linked List| Solution'
Pepcoding 7 mins
K Reverse in Linked List| Solution
YouTube video 'HackerRank - Reverse Linked List | Full solution with visuals | Study Algorithms'
Nikhil Lohia 15 mins
HackerRank - Reverse Linked List | Full solution with visuals | Study Algorithms
YouTube video 'Reverse a Linked List - Data Iterative | Solution'
Pepcoding 3 mins
Reverse a Linked List - Data Iterative | Solution
YouTube video 'Reverse a Linked List - Pointer Iterative | Solution'
Pepcoding 9 mins
Reverse a Linked List - Pointer Iterative | Solution
YouTube video 'Reverse A Linked List | Linked List'
Pepcoding 12 mins
Reverse A Linked List | Linked List
YouTube video 'Reverse a Linked List using Pointers - Recursive | Solution'
Pepcoding 5 mins
Reverse a Linked List using Pointers - Recursive | Solution
YouTube video 'HackerRank Reverse A Linked List Solution Explained - Java'
Nick White 6 mins
HackerRank Reverse A Linked List Solution Explained - Java
YouTube video 'Reverse a Linked List - Data Recursive | Solution'
Pepcoding 17 mins
Reverse a Linked List - Data Recursive | Solution
YouTube video '206. Reverse Linked List || Java || Leetcode || Hindi'
Coding Sphere 5 mins
206. Reverse Linked List || Java || Leetcode || Hindi
YouTube video 'LeetCode 206: Reverse Linked List RECURSIVELY - Interview Prep Ep 60'
Fisher Coder 13 mins
LeetCode 206: Reverse Linked List RECURSIVELY - Interview Prep Ep 60
YouTube video 'HackerRank Reverse A Doubly Linked List Solution Explained - Java'
Nick White 5 mins
HackerRank Reverse A Doubly Linked List Solution Explained - Java
YouTube video 'Display Reverse Linked List - Recursive | Solution'
Pepcoding 4 mins
Display Reverse Linked List - Recursive | Solution
YouTube video '[Java] Leetcode 206. Reverse Linked List [LinkedList Reversal #1]'
Eric Programming 7 mins
[Java] Leetcode 206. Reverse Linked List [LinkedList Reversal #1]
YouTube video 'Reverse Linked List - LeetCode Solutions - LeetCode Problems'
One Code Man 3 mins
Reverse Linked List - LeetCode Solutions - LeetCode Problems
YouTube video 'Reverse A Linked List Using addFirst | Leetcode 206 Reverse Linked List | Linked list'
Pepcoding 9 mins
Reverse A Linked List Using addFirst | Leetcode 206 Reverse Linked List | Linked list
YouTube video 'Reverse a Linked List - Pointer Iterative | Solution'
Pepcoding 3 mins
Reverse a Linked List - Pointer Iterative | Solution
YouTube video 'Reverse Linked List - LeetCode  206 - Python (Iterative and Recursive)'
Deepti Talesra 16 mins
Reverse Linked List - LeetCode 206 - Python (Iterative and Recursive)
YouTube video 'Reverse Linked List Recursively'
Knowledge Center 17 mins
Reverse Linked List Recursively
YouTube video 'Leetcode | 206. Reverse Linked List | Easy | Java Solution'
Developer Docs 7 mins
Leetcode | 206. Reverse Linked List | Easy | Java Solution
YouTube video 'Reverse Linked List | Leetcode - 206'
Algorithms Made Easy 13 mins
Reverse Linked List | Leetcode - 206
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

7 similar problems

Solved On The Same Day

39 easy 31 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality