Skip to content

Commit 18a6e9a

Browse files
committed
feat: Upload remove-nth-node-from-end-of-list (typescript)
1 parent 6732d7c commit 18a6e9a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Source: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
3+
* Solution: ๋‘ ๊ฐœ์˜ ํฌ์ธํ„ฐ๋ฅผ ์ด์šฉํ•ด n๋ฒˆ์งธ ๋…ธ๋“œ๋ฅผ ์ฐพ์•„ ์‚ญ์ œ
4+
*
5+
* ์‹œ๊ฐ„๋ณต์žก๋„: O(N) - ๋‘ ๊ฐœ์˜ ํฌ์ธํ„ฐ๊ฐ€ ํ•œ๋ฒˆ์”ฉ ์ˆœํšŒ
6+
* ๊ณต๊ฐ„๋ณต์žก๋„: O(1) - ์ƒ์ˆ˜๋งŒํผ์˜ ๊ณต๊ฐ„ ์‚ฌ์šฉ
7+
*/
8+
9+
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
10+
if (!head) return null;
11+
12+
const dummy = new ListNode(0, head);
13+
let slow: ListNode | null = dummy;
14+
let fast: ListNode | null = dummy;
15+
16+
for (let i = 0; i <= n; i++) {
17+
if (!fast) return head;
18+
fast = fast.next;
19+
}
20+
21+
while (fast) {
22+
slow = slow!.next;
23+
fast = fast.next;
24+
}
25+
26+
if (slow && slow.next) {
27+
slow.next = slow.next.next;
28+
}
29+
30+
return dummy.next;
31+
}

0 commit comments

Comments
ย (0)