Skip to content

Commit

Permalink
feat: remove-nth-node-from-end-of-list solution
Browse files Browse the repository at this point in the history
  • Loading branch information
YeomChaeeun committed Feb 27, 2025
1 parent e7efcea commit 660e507
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions remove-nth-node-from-end-of-list/YeomChaeeun.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
/**
* n번째 노드 제거하기
* 알고리즘 복잡도
* - 시간 복잡도: O(n)
* - 공간 복잡도: O(n)
* @param head
* @param n
*/
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
let stack: ListNode[] = [];
let node = head;

while (node) {
stack.push(node);
node = node.next;
}

// 첫 번째 노드를 제거하는 경우 추가
if (stack.length - n - 1 < 0) {
return head?.next || null;
}

const prevNode = stack[stack.length - n - 1];
prevNode.next = prevNode.next?.next || null;

return head;
}

0 comments on commit 660e507

Please sign in to comment.