Reverse a Linked List

def reverseList(self, head: ListNode) -> ListNode:
    current = head
    while (current and
        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 ( is not None):
            next =
            before = self.reverseHelper(next)
   = head
   = 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

Like this post? Subscribe for more.

Kevin Chow
Kevin Chow
Fledging Computer Scientist