[Leetcode] 206. Reverse Linked List

서해빈·2021년 4월 21일
0

코딩테스트

목록 보기
52/65

문제 바로가기

Iterative

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

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        
        prevNode = None
        while head:
            nextNode = head.next
            head.next = prevNode
            prevNode, head = head, nextNode
            
        return prevNode

recursive

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

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        
        root_rev = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return root_rev

0개의 댓글