LeetCode 206 – Python 3 (Week 3 – 05)

Solution 1: Iterative

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        #Iterative
        dummy = ListNode(float('-inf'))

        while head:
            dummy.next, head.next, head = head, dummy.next, head.next
        return dummy.next
            

Time complexity is O(n). Space complexity is O(1).

Solution 2: Recursive

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        #Recursive
        if not head or not head.next: return head
        
        left = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return left

Time complexity is O(n). Space complexity is O(n).

Leave a comment

Design a site like this with WordPress.com
Get started