Skip to content

Commit 355cfd6

Browse files
committed
remove-nth-node-from-end-of-list solution
1 parent 9fbd3df commit 355cfd6

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+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @param {number} n
11+
* @return {ListNode}
12+
*/
13+
var removeNthFromEnd = function (head, n) {
14+
if (!head) {
15+
return null;
16+
}
17+
18+
let node = head;
19+
20+
const list = [];
21+
22+
while (node) {
23+
list.push(node);
24+
node = node.next;
25+
}
26+
27+
const targetIndex = list.length - n - 1;
28+
29+
if (targetIndex === -1 && list.length === 1) {
30+
return null;
31+
}
32+
33+
if (targetIndex === -1) {
34+
return head.next;
35+
}
36+
37+
if (list[targetIndex]) {
38+
list[targetIndex].next = list[targetIndex]?.next?.next || null;
39+
}
40+
41+
return head;
42+
};
43+
44+
// ์‹œ๊ฐ„๋ณต์žก๋„ O(n) - ๋…ธ๋“œ๋ฅผ ํ•œ๋ฒˆ ์ˆœํšŒํ•˜์—ฌ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅ
45+
// ๊ณต๊ฐ„๋ณต์žก๋„ O(n) - ์ˆœํšŒ ์ดํ›„์— ์ œ๊ฑฐํ•  ๋…ธ๋“œ์˜ ๋ฐ”๋กœ ์•ž ๋…ธ๋“œ๋ ˆ ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•˜์—ฌ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ๋ฐฐ์—ด์— ์ €์žฅ

0 commit comments

Comments
ย (0)