Reverse a Linked List
Easy
Linked ListRecursion
Problem
Given the head of a singly linked list, reverse it and return the new head.
Example 1
Input: 1 -> 2 -> 3 -> 4 -> 5 -> null
Output: 5 -> 4 -> 3 -> 2 -> 1 -> null
Example 2
Input: 1 -> 2 -> null
Output: 2 -> 1 -> null
Example 3
Input: null
Output: null
Constraints
- 0 ≤ list length ≤ 5000
- −5000 ≤ Node.val ≤ 5000
Approach — Linked List
This is a Linked List problem. The idea: rework the list with careful pointer manipulation — often a dummy head and fast/slow pointers — in a single pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(1) space.
Solution code
Python
class Solution:
def reverseList(self, head):
prev = None
while head:
nxt = head.next
head.next = prev
prev = head
head = nxt
return prev
Java
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Reverse a Linked List interactively → ← All solutions