-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: remove-nth-node-from-end-of-list solution
- Loading branch information
1 parent
e7efcea
commit 660e507
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |