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