Skip to content

Commit 3f7d0f8

Browse files
committed
solve: Remove Nth Node From End of List
1 parent 9e611b5 commit 3f7d0f8

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
Constraints:
3+
- The number of nodes in the list is sz.
4+
- 1 <= sz <= 30
5+
- 0 <= Node.val <= 100
6+
- 1 <= n <= sz
7+
8+
Time Complexity: O(n)
9+
- 여기서 n은 리스트의 길이, 리스트를 한 번만 순회함
10+
11+
Space Complexity: O(1)
12+
- 추가 공간을 사용하지 않음, 정해진 개수의 변수만 사용
13+
14+
풀이방법:
15+
1. fast 포인터를 n번 앞으로 이동
16+
2. base case: 만약 fast가 None이라면, 첫 번째 노드를 제거함
17+
3. fast.next가 None일 때까지 두 포인터를 함께 이동
18+
4. slow의 다음 노드를 제거함 (slow.next = slow.next.next로 연결을 끊어냄)
19+
"""
20+
# Definition for singly-linked list.
21+
# class ListNode:
22+
# def __init__(self, val=0, next=None):
23+
# self.val = val
24+
# self.next = next
25+
class Solution:
26+
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
27+
slow = head
28+
fast = head
29+
30+
for i in range(n):
31+
fast = fast.next
32+
33+
if not fast:
34+
return head.next
35+
36+
while fast.next:
37+
slow = slow.next
38+
fast = fast.next
39+
40+
slow.next = slow.next.next
41+
42+
return head

0 commit comments

Comments
 (0)