Skip to content

Commit 7764d7f

Browse files
committed
remove-nth-node-from-end-of-list solution (py)
1 parent 7c85ff4 commit 7764d7f

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
뒤에서 n번째 노드를 없애고, linked list head를 반환해라
3+
4+
TC: O(N), 리스트 한 번 순회
5+
SC: O(1), 포인터 2개만 사용
6+
"""
7+
8+
from typing import Optional
9+
10+
# Definition for singly-linked list.
11+
class ListNode:
12+
def __init__(self, val=0, next=None):
13+
self.val = val
14+
self.next = next
15+
16+
17+
class Solution:
18+
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
19+
# dummy node를 head 앞에 두어 edge case(head 삭제 등) 처리
20+
dummy = ListNode(0, head)
21+
first = dummy
22+
second = dummy
23+
24+
# first를 n+1칸 먼저 이동 -> 두 포인터 사이 간격이 n
25+
for _ in range(n + 1):
26+
first = first.next
27+
28+
# first가 끝에 도달할 때까지 두 포인터 함께 전진
29+
while first:
30+
first = first.next
31+
second = second.next
32+
33+
# second의 다음 노드가 삭제 대상이므로 연결 건너뛰기
34+
second.next = second.next.next
35+
36+
# 실제 head는 dummy.next에 있음
37+
return dummy.next

0 commit comments

Comments
 (0)