Skip to content

Commit 7f6029e

Browse files
committed
add: solve DaleStudy#248 Remove Nth Node From End of List with ts
1 parent 5a2f265 commit 7f6029e

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* val: number;
5+
* next: ListNode | null;
6+
* constructor(val?: number, next?: ListNode | null) {
7+
* this.val = (val === undefined ? 0 : val);
8+
* this.next = (next === undefined ? null : next);
9+
* }
10+
* }
11+
*/
12+
13+
/**
14+
* ์ฃผ์–ด์ง„ ๋‹จ์ผ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์—์„œ ๋’ค์—์„œ N๋ฒˆ์งธ ๋…ธ๋“œ๋ฅผ ์ œ๊ฑฐํ•˜๋Š” ํ•จ์ˆ˜
15+
* @param {ListNode | null} head - ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ์‹œ์ž‘ ๋…ธ๋“œ
16+
* @param {number} n - ๋’ค์—์„œ n๋ฒˆ์งธ ๋…ธ๋“œ
17+
* @returns {ListNode | null} - n๋ฒˆ์งธ ๋…ธ๋“œ๊ฐ€ ์ œ๊ฑฐ๋œ ์ƒˆ๋กœ์šด ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ์‹œ์ž‘ ๋…ธ๋“œ
18+
*
19+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(N)
20+
* - ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ•œ ๋ฒˆ ์ˆœํšŒํ•˜์—ฌ ๊ธธ์ด๋ฅผ ์ฐพ๊ณ , ๋‹ค์‹œ ํ•œ ๋ฒˆ ์ˆœํšŒํ•˜์—ฌ ๋…ธ๋“œ๋ฅผ ์‚ญ์ œ (2N)
21+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)
22+
* - ์ถ”๊ฐ€์ ์ธ ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ๋ฉฐ, ํฌ์ธํ„ฐ๋งŒ ์‚ฌ์šฉํ•˜์—ฌ ์ฒ˜๋ฆฌ
23+
*/
24+
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
25+
let headlength = 0, cur = head;
26+
27+
// ์ „์ฒด ๊ธธ์ด ๊ตฌํ•˜๊ธฐ
28+
while (cur) {
29+
headlength++;
30+
cur = cur.next;
31+
}
32+
33+
// ์‚ญ์ œํ•  ๋…ธ๋“œ ์œ„์น˜ ๊ณ„์‚ฐ (length - n)
34+
let dummy = new ListNode(0, head);
35+
cur = dummy;
36+
for (let i = 0; i < headlength - n; i++) {
37+
cur = cur.next;
38+
}
39+
40+
// ๋…ธ๋“œ ์‚ญ์ œ (n๋ฒˆ์งธ ๋…ธ๋“œ ์ œ๊ฑฐ)
41+
cur.next = cur.next?.next || null;
42+
43+
return dummy.next;
44+
}
45+

0 commit comments

Comments
ย (0)