Skip to content

Commit c20cebb

Browse files
committed
remove-nth-node-from-end-of-list solution
1 parent cdf821d commit c20cebb

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
8+
9+
# 투포인터
10+
# 시간복잡도 O(n), 공간복잡도 O(1)
11+
12+
# 더미 노드 사용(head삭제되는경우대비)
13+
dummy = ListNode(0, head)
14+
slow, fast = dummy, dummy
15+
16+
# fast를 n칸 이동(slow와의 간격n으로 유지)
17+
for _ in range(n):
18+
fast = fast.next
19+
20+
# fast가 끝에 도달할때까지 slow와 한 칸씩 이동
21+
while fast.next:
22+
fast = fast.next
23+
slow = slow.next
24+
25+
# slow.next = 삭제대상, 건너뛰고연결(삭제처리)
26+
slow.next = slow.next.next
27+
28+
# 새로운 head 반환
29+
return dummy.next

0 commit comments

Comments
 (0)