Faaez Razeen

Reverse A Linked List

  • 1 min read
  • LC-Easy
  • Linked List

3 years ago

Solution

TimeSpaceExplanation
O()O()
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: prev = None curr = head while curr: next = curr.next curr.next = prev prev = curr curr = next return prev

Recursive

def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: if head is None: return None new_head = head if head.next: new_head = self.reverseList(head.next) head.next.next = head head.next = None return new_head