Reverse Linked List
EasyGiven the head of a singly linked list, reverse the list and return the reversed list.
Examples
| Input | Output |
|---|---|
| head = [1,2,3,4,5] | [5,4,3,2,1] |
| head = [1,2] | [2,1] |
Python Solution
def reverse_list(head: ListNode | None) -> ListNode | None:
prev = None
while head:
next_node = head.next
head.next = prev
prev = head
head = next_node
return prevJavaScript Solution
function reverseList(head) {
let prev = null;
while (head) {
const next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}Step-by-Step Explanation
- Use three pointers: prev (initially null), current (head), and next.
- For each node: save next, point current.next to prev, advance prev and current.
- Continue until head is null. prev will be the new head.
Complexity Analysis
| Time | O(n) |
| Space | O(1) |
Tags
Linked ListRecursion
Related Problems
All Problems
Two SumReverse a StringPalindrome CheckFizzBuzzBinary SearchMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Remove Duplicates from Sorted ArrayNth Fibonacci NumberValid AnagramFirst Unique CharacterClimbing StairsRoman to IntegerBest Time to Buy and Sell StockContains DuplicateMove ZeroesIntersection of Two ArraysLongest Common Prefix