206. Reverse Linked List - recursive

# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ # base case if head == None or head.next == None: return head # recursion newhead = self.reverseList(head.next) # find tail tail = newhead while(tail.next != None): tail = tail.next # change tail with remaining node tail.next = head head.next = None return newhead
One pass!

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.