Skip to content

Commit

Permalink
feat: Upload remove-nth-node-from-end-of-list (typescript)
Browse files Browse the repository at this point in the history
  • Loading branch information
mike2ox committed Feb 25, 2025
1 parent 6732d7c commit 18a6e9a
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions remove-nth-node-from-end-of-list/mike2ox.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* Source: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
* Solution: ๋‘ ๊ฐœ์˜ ํฌ์ธํ„ฐ๋ฅผ ์ด์šฉํ•ด n๋ฒˆ์งธ ๋…ธ๋“œ๋ฅผ ์ฐพ์•„ ์‚ญ์ œ
*
* ์‹œ๊ฐ„๋ณต์žก๋„: O(N) - ๋‘ ๊ฐœ์˜ ํฌ์ธํ„ฐ๊ฐ€ ํ•œ๋ฒˆ์”ฉ ์ˆœํšŒ
* ๊ณต๊ฐ„๋ณต์žก๋„: O(1) - ์ƒ์ˆ˜๋งŒํผ์˜ ๊ณต๊ฐ„ ์‚ฌ์šฉ
*/

function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
if (!head) return null;

const dummy = new ListNode(0, head);
let slow: ListNode | null = dummy;
let fast: ListNode | null = dummy;

for (let i = 0; i <= n; i++) {
if (!fast) return head;
fast = fast.next;
}

while (fast) {
slow = slow!.next;
fast = fast.next;
}

if (slow && slow.next) {
slow.next = slow.next.next;
}

return dummy.next;
}

0 comments on commit 18a6e9a

Please sign in to comment.