Published:
Updated:

  • Reference
  • μž¬κ·€ 방식이 쑰금 더 느림
    • Runtime 42 ms
    • Beats 39.11%
  • μ‹œκ°„λ³΅μž‘λ„: $O(N)$


Solution

# Definition for singly-linked list.
from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        prev = None
        curr = head

        # νŒŒμ΄μ¬μ—μ„œ λ’€μ§‘λŠ” 건 κ·Έλƒ₯ λ˜μ§€λ§Œ, μžλ°”μ—μ„œλŠ” μ΄λ ‡κ²Œ λ’€μ§‘μ—ˆμ—ˆμ§€!
        # next -> prev -> current
        while curr:
            tmp = curr.next
            curr.next = prev
            prev = curr
            curr = tmp

        return prev

        # μž¬κ·€ 방식
        # if not head:
        #     return None
        #
        # new_head = head
        # if head.next:
        #     new_head = self.reverseList(head.next)
        #     head.next.next = head
        # head.next = None
        #
        # return new_head

Leave a comment