Skip to content

Commit 2d70f08

Browse files
authored
[ PS ] : Remove Nth Node From End of List
1 parent 424cc78 commit 2d70f08

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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+
// 첫 번째 풀이
10+
// 시간복잡도: O(n)
11+
// 공간복잡도: O(n)
12+
/**
13+
* @param {ListNode} head
14+
* @param {number} n
15+
* @return {ListNode}
16+
*/
17+
const removeNthFromEnd = function (head, n) {
18+
function dfs(node) {
19+
// 마지막 노드이면 1 반환
20+
if (!node.next) {
21+
return 1;
22+
}
23+
24+
const nth = dfs(node.next);
25+
if (nth === n) {
26+
node.next = node.next.next ?? null;
27+
}
28+
29+
return nth + 1;
30+
}
31+
32+
if (dfs(head) === n) {
33+
return head.next;
34+
}
35+
36+
return head;
37+
};
38+
39+
// 두 번째 풀이
40+
// 시간복잡도: O(n)
41+
// 공간복잡도: O(1)
42+
const removeNthFromEnd = function (head, n) {
43+
const temp = new ListNode(0, head);
44+
let tail = temp;
45+
let prev = temp; // 뒤에서 n번째 노드
46+
47+
for (let i = 0; i < n; i++) {
48+
tail = tail.next;
49+
}
50+
51+
while (tail.next) {
52+
tail = tail.next;
53+
prev = prev.next;
54+
}
55+
56+
prev.next = prev.next.next;
57+
58+
return temp.next;
59+
};

0 commit comments

Comments
 (0)