Given the beginning of a singly linked list head, reverse the list, and return the new beginning of the list.
Example 1:
Input: head = [0,1,2,3]
Output: [3,2,1,0] Example 2:
Input: head = []
Output: []
In [11]:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
- Hold 2 positions (prev=None, curr=head) like grabbing a chain's start
- For each link: save next position, flip arrow backwards, move both positions forward
- When curr hits None, prev becomes new head
In [12]:
def reverseLL(head:ListNode):
prev,curr=None,head
while curr:
temp = curr.next
curr.next=prev
prev = curr
curr = temp
return prev