Skip to content

Commit ae3bd32

Browse files
committed
solve 2
1 parent 938ea55 commit ae3bd32

File tree

1 file changed

+60
-0
lines changed
  • remove-nth-node-from-end-of-list

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
'''
2+
์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
3+
๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)
4+
'''
5+
from typing import Optional
6+
7+
# Definition for singly-linked list.
8+
class ListNode:
9+
def __init__(self, val=0, next=None):
10+
self.val = val
11+
self.next = next
12+
13+
# ๋ฆฌ์ŠคํŠธ ์ด ๊ธธ์ด ๊ณ„์‚ฐ
14+
class Solution:
15+
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
16+
# ๋ฆฌ์ŠคํŠธ ๊ธธ์ด ๊ณ„์‚ฐ
17+
length = 1
18+
current = head
19+
while current.next:
20+
length += 1
21+
current = current.next
22+
23+
# ์ œ๊ฑฐํ•  ๋…ธ๋“œ๊ฐ€ ์ฒซ ๋ฒˆ์งธ(head)์ธ ๊ฒฝ์šฐ
24+
if n == length:
25+
return head.next
26+
27+
index = 0
28+
current = head
29+
30+
# ์ œ๊ฑฐ ๋Œ€์ƒ ๋…ธ๋“œ ์ „๊นŒ์ง€ ์ด๋™
31+
for _ in range(length - n - 1):
32+
current = current.next
33+
34+
# ์ œ๊ฑฐ ๋Œ€์ƒ ๋…ธ๋“œ ๊ฑด๋„ˆ๋›ฐ๊ธฐ
35+
current.next = current.next.next
36+
37+
return head
38+
39+
# Two-Pointer
40+
class Solution:
41+
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
42+
first = second = head
43+
44+
# 1. `first`๋ฅผ n ๋งŒํผ ์ด๋™ โ†’ `second`์™€์˜ ๊ฐ„๊ฒฉ ์œ ์ง€
45+
for _ in range(n):
46+
first = first.next
47+
48+
# ์ œ๊ฑฐ ๋Œ€์ƒ์ด ์ฒซ๋ฒˆ์งธ ๋…ธ๋“œ์ธ ๊ฒฝ์šฐ, next ๋ฐ˜ํ™˜
49+
if not first:
50+
return head.next
51+
52+
# 2. `first`๊ฐ€ ๋๊นŒ์ง€ ๊ฐˆ ๋•Œ๊นŒ์ง€ `second`๋„ ํ•จ๊ป˜ ์ด๋™
53+
while first.next:
54+
first = first.next
55+
second = second.next
56+
57+
# 3. `second.next`๊ฐ€ ๊ฐ€๋ฆฌํ‚ค๋Š” ๋…ธ๋“œ ์ œ๊ฑฐ
58+
second.next = second.next.next
59+
60+
return head

0 commit comments

Comments
ย (0)