Reverse A Linked List
- 1 min read
- LC-Easy
- Linked List
Solution
- I... don't really know how to explain this. Just solve the problem I guess.
| Time | Space | Explanation |
|---|
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
- Draw out the solution on paper. YOU'LL UNDERSTAND.
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