Skip to content

Commit

Permalink
solve 2
Browse files Browse the repository at this point in the history
  • Loading branch information
pmjuu committed Feb 26, 2025
1 parent 938ea55 commit ae3bd32
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions remove-nth-node-from-end-of-list/pmjuu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
'''
์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)
'''
from typing import Optional

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

# ๋ฆฌ์ŠคํŠธ ์ด ๊ธธ์ด ๊ณ„์‚ฐ
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
# ๋ฆฌ์ŠคํŠธ ๊ธธ์ด ๊ณ„์‚ฐ
length = 1
current = head
while current.next:
length += 1
current = current.next

# ์ œ๊ฑฐํ•  ๋…ธ๋“œ๊ฐ€ ์ฒซ ๋ฒˆ์งธ(head)์ธ ๊ฒฝ์šฐ
if n == length:
return head.next

index = 0
current = head

# ์ œ๊ฑฐ ๋Œ€์ƒ ๋…ธ๋“œ ์ „๊นŒ์ง€ ์ด๋™
for _ in range(length - n - 1):
current = current.next

# ์ œ๊ฑฐ ๋Œ€์ƒ ๋…ธ๋“œ ๊ฑด๋„ˆ๋›ฐ๊ธฐ
current.next = current.next.next

return head

# Two-Pointer
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
first = second = head

# 1. `first`๋ฅผ n ๋งŒํผ ์ด๋™ โ†’ `second`์™€์˜ ๊ฐ„๊ฒฉ ์œ ์ง€
for _ in range(n):
first = first.next

# ์ œ๊ฑฐ ๋Œ€์ƒ์ด ์ฒซ๋ฒˆ์งธ ๋…ธ๋“œ์ธ ๊ฒฝ์šฐ, next ๋ฐ˜ํ™˜
if not first:
return head.next

# 2. `first`๊ฐ€ ๋๊นŒ์ง€ ๊ฐˆ ๋•Œ๊นŒ์ง€ `second`๋„ ํ•จ๊ป˜ ์ด๋™
while first.next:
first = first.next
second = second.next

# 3. `second.next`๊ฐ€ ๊ฐ€๋ฆฌํ‚ค๋Š” ๋…ธ๋“œ ์ œ๊ฑฐ
second.next = second.next.next

return head

0 comments on commit ae3bd32

Please sign in to comment.