LeetCode 206.

LeetCode 206

Approach 1. Recursive

Time Complexity: O(n), Space Complexity: O(n)

class Solution:
    def reverseList(self, head):
        if not head or not head.next: 
            return head
        temp = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return temp

Approach 2. Iterative

Time Complexity: O(n), Space Complexity: O(1)

class Solution:
    def reverseList(self, head):
        prev = None
        curr = head
        while curr:
            temp = curr.next
            curr.next = prev
            prev = curr
            curr = temp
        return prev

이렇게 기본적인 문제들 정도는 접근 방식을 외워두는 것도 좋은 것 같다.

좋은 웹페이지 즐겨찾기