File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 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
You canโt perform that action at this time.
0 commit comments