Skip to content

Commit 660e507

Browse files
committedFeb 27, 2025
feat: remove-nth-node-from-end-of-list solution
1 parent e7efcea commit 660e507

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
 
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
* n번째 노드 제거하기
14+
* 알고리즘 복잡도
15+
* - 시간 복잡도: O(n)
16+
* - 공간 복잡도: O(n)
17+
* @param head
18+
* @param n
19+
*/
20+
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
21+
let stack: ListNode[] = [];
22+
let node = head;
23+
24+
while (node) {
25+
stack.push(node);
26+
node = node.next;
27+
}
28+
29+
// 첫 번째 노드를 제거하는 경우 추가
30+
if (stack.length - n - 1 < 0) {
31+
return head?.next || null;
32+
}
33+
34+
const prevNode = stack[stack.length - n - 1];
35+
prevNode.next = prevNode.next?.next || null;
36+
37+
return head;
38+
}

0 commit comments

Comments
 (0)