Algo-Sim › Linked Lists
Reverse Linked List
Easy · Linked Lists · step through it in Java, Python and C++ on your own input
Reverse a singly linked list in place by flipping each next pointer, with prev, curr and next.
Problem
Given the head of a singly linked list, reverse the list in place and return the new head.
Constraints
- 0 ≤ number of nodes ≤ 5000
- -5000 ≤ Node.val ≤ 5000
- O(1) extra space: relink nodes, don't copy them
Edge cases to test
- Empty list
- One node
- Two nodes
Follow-up questions
- Can you reverse only positions left..right?
- Walk to node left − 1 and reverse the next right − left + 1 nodes, reconnecting both ends (LC 92): O(n), one pass.
- Iterative or recursive?
- Iterative uses O(1) space; recursion is shorter but uses O(n) stack and can overflow on long lists.
Solution
Java
public 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;
}Python
def reverse_list(head):
prev, curr = None, head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prevC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
ListNode *reverseList(ListNode *head) {
ListNode *prev = nullptr, *curr = head;
while (curr != nullptr) {
ListNode *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};
More Linked Lists problems
- Reverse Linked List (Recursive) (Easy)
- Merge Two Sorted Lists (Easy)
- Middle of the Linked List (Easy)
- Palindrome Linked List (Easy)
- Linked List Cycle (Easy)
- Linked List Cycle II (Medium)
- Intersection of Two Linked Lists (Easy)
- Find the Duplicate Number (Medium)
- Remove Nth Node From End of List (Medium)
- Reorder List (Medium)
- Sort List (Medium)
- Add Two Numbers (Medium)
- Copy List with Random Pointer (Medium)
- Reverse Nodes in k-Group (Hard)