206. Reverse Linked List
[Easy] “Reverse a singly linked list."
Python3:
class Solution:
# # iterative
# def reverseList(self, head: ListNode) -> ListNode:
# prev = None
# curr = head
# while curr:
# # save next node
# next_node = curr.next
# # swap with previous node
# curr.next = prev
# # shift current node back
# prev = curr
# curr = next_node
# return prev
# recursive
def reverseList(self, head: ListNode) -> ListNode:
if (head == None) or (head.next == None):
return head
else:
next_node = self.reverseList(head.next)
# swap with next node's pointer
head.next.next = head
# erase head
head.next = None
return next_node