Lists, stacks & queues / Beginner
Reverse a Linked List Visualizer
Walk the list once. At each node, save next, point the node back to prev, then move prev and curr one step forward.
Start the Reverse a Linked List simulation → Step forward and back, change the input, follow the code line by line in Java, Python, C++, C or JavaScript. Free, no sign-up.
Time and space complexity
| Best time | O(n) |
|---|---|
| Average time | O(n) |
| Worst time | O(n) |
| Extra space | O(1) |
Worked example, step by step
The same steps the simulator shows, on a small input.
- prev starts at null and curr at the head (1).
- Save next = 2 so the rest of the list is not lost.
- Point 1 back to null.
- Move prev to 1 and curr to 2.
- Save next = 3 so the rest of the list is not lost.
- Point 2 back to 1.
- Move prev to 2 and curr to 3.
- Save next = 4 so the rest of the list is not lost.
- Point 3 back to 2.
- Move prev to 3 and curr to 4.
- Save next = 5 so the rest of the list is not lost.
- Point 4 back to 3.
- Move prev to 4 and curr to 5.
- Save next = null so the rest of the list is not lost.
- Point 5 back to 4.
- Move prev to 5 and curr to null.
- curr is null, so we are done. The new head is 5.
Reverse a linked list in Java, Python, C++, C and JavaScript
ListNode reverseList(ListNode head) {
ListNode prev = null, curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
def reverse_list(head):
prev, curr = None, head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
ListNode* reverseList(ListNode* head) {
ListNode *prev = nullptr, *curr = head;
while (curr) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode *prev = NULL, *curr = head;
while (curr) {
struct ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
function reverseList(head) {
let prev = null, curr = head;
while (curr !== null) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}In an interview
LeetCode 206, Reverse Linked List.
Draw the three pointers before writing code. Most bugs come from changing curr.next before saving it.