Reverse a singly linked list.
Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output: 5 -> 4 -> 3 -> 2 -> 1 -> NULL
What is the structure of the linked list node?
Each node will have two fields: val
(the value) and next
(the pointer to the next node).
Are there any constraints on the values of the linked list’s nodes? No specific constraints other than typical integer values.
Do we need to handle any specific edge cases?
head
is None
).prev
as None
and curr
as the head of the list.next
pointer to point to prev
.prev
and curr
one step forward.prev
pointer will eventually point to the new head of the reversed list.class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head: ListNode) -> ListNode:
prev = None
curr = head
while curr:
next_temp = curr.next # Store the next node
curr.next = prev # Reverse the link
prev = curr # Move prev to current node
curr = next_temp # Move curr to next node
return prev
# Helper function to print the list (for understanding/debugging purposes)
def printList(head: ListNode):
while head:
print(head.val, end=" -> ")
head = head.next
print("NULL")
This approach ensures that the linked list is reversed efficiently with minimal memory overhead.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?