- 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