Reverse Linked List
Easy · Linked lists
Jump to codeReverse a singly linked list by changing its next pointers and return the new head. The list may be empty.
Examples
Example 1
head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2
head = [1,2]
Output: [2,1]
Constraints
- 0 <= The length of the list <= 1000.
- -1000 <= Node.val <= 1000
Function contract
Linked lists are displayed as value arrays. Your code receives ListNode objects with val and next fields.
Need a hint?
Save the next node before overwriting its pointer.
Asked in real interviews
Candidates reported versions of Reverse Linked List from these company interviews. Some company questions are locked and open with Premium or XP.
- Reverse a Singly Linked ListGrammarly
- Reverse a linked listLinkedIn
- Reverse a Singly Linked ListByteDance
Solution approach
Maintain previous = null and current = head. Save current.next, point current.next to previous, then advance previous and current. When current becomes null, previous is the reversed head. No new list nodes are necessary.
Complexity
O(n) time and O(1) extra space.
Python reference solution
def reverseList(head):
previous = None
while head:
following = head.next
head.next = previous
previous, head = head, following
return previous
JavaScript solution
function reverseList(head) {
let previous = null;
while (head) {
const following = head.next;
head.next = previous;
previous = head;
head = following;
}
return previous;
}
Java solution
import java.util.*;
class Solution {
public ListNode reverseList(ListNode head) {
ListNode previous = null;
while (head != null) {
ListNode following = head.next;
head.next = previous;
previous = head;
head = following;
}
return previous;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* previous = nullptr;
while (head) {
ListNode* following = head->next;
head->next = previous;
previous = head;
head = following;
}
return previous;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 7 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
1,
2,
3,
4,
5
]
][ 5, 4, 3, 2, 1 ]
[
[
1,
2
]
][ 2, 1 ]
[ [] ]
[]
[
[
1
]
][ 1 ]
[
[
1,
2,
3
]
][ 3, 2, 1 ]
Drafts are saved per language in this browser when storage is available.