Reverse Linked List
easy · pointer reversal
You are given the head of a singly linked list. Reverse the list and return the head of the reversed list. Do it in place — do not build a new list or copy the values into an array. An empty list stays empty. The nodes are ListNode objects with val and next; the starter code defines the class.
Constraints
0 ≤ nodes ≤ 5000; -5000 ≤ val ≤ 5000.
Examples
[1,2,3,4,5] → [5,4,3,2,1]
[1,2] → [2,1]
[] → []
Starter code
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_list(head: ListNode | None) -> ListNode | None:
pass
Loading editor…
Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.
Return to the Python interpreter