Reverse a Linked List
def reverseList(self, head: ListNode) -> ListNode:
current = head
while (current and current.next):
next = current.next
current.next = next.next
next.next = head
head = next
return head
This is a real basic problem, but it can be tricky. You should have it down cold for any interviews.
Do more of these basic problems series.
The real key here is memory management, how many pointers do you need to do the task?
Also do it iteratively (faulty solution to improve on)
def reverseHelper(self, head):
if (head.next is not None):
next = head.next
before = self.reverseHelper(next)
before.next = head
head.next = None
print("before", before)
print("head", head)
return head
# who returns what?
def reverseList(self, head: ListNode) -> ListNode:
tail = self.reverseHelper(head)
print("tail", tail)
if ( tail):
return None
return tail.next