Reverse Linked List
Examples
Example 1:
Input: head = [0,1,2,3]
Output: [3,2,1,0]
Example 2:
Input: head = []
Output: []
Example 1:
Input: head = [0,1,2,3]
Output: [3,2,1,0]
Example 2:
Input: head = []
Output: []
Given the beginning of a singly linked list head, reverse the list, and return the new beginning of the list.
0 <= The length of the list <= 1000.-1000 <= Node.val <= 1000Iteratively reverse the list using two pointers. Walk through the list, redirect next to point to the previous node, then advance both pointers. This handles empty and single-node lists naturally.
At each step, the portion already processed is reversed and correctly linked to prev. Redirecting curr.next to prev preserves the reversed segment while keeping access to the remaining nodes via a temporary pointer. When the scan finishes, prev is the new head.
O(n)O(1)class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
curr = head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev