Skip to content

Commit

Permalink
remove-nth-node-from-end-of-list solution
Browse files Browse the repository at this point in the history
  • Loading branch information
jdy8739 committed Feb 24, 2025
1 parent 9fbd3df commit 355cfd6
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions remove-nth-node-from-end-of-list/jdy8739.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function (head, n) {
if (!head) {
return null;
}

let node = head;

const list = [];

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

const targetIndex = list.length - n - 1;

if (targetIndex === -1 && list.length === 1) {
return null;
}

if (targetIndex === -1) {
return head.next;
}

if (list[targetIndex]) {
list[targetIndex].next = list[targetIndex]?.next?.next || null;
}

return head;
};

// ์‹œ๊ฐ„๋ณต์žก๋„ O(n) - ๋…ธ๋“œ๋ฅผ ํ•œ๋ฒˆ ์ˆœํšŒํ•˜์—ฌ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅ
// ๊ณต๊ฐ„๋ณต์žก๋„ O(n) - ์ˆœํšŒ ์ดํ›„์— ์ œ๊ฑฐํ•  ๋…ธ๋“œ์˜ ๋ฐ”๋กœ ์•ž ๋…ธ๋“œ๋ ˆ ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•˜์—ฌ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ๋ฐฐ์—ด์— ์ €์žฅ

0 comments on commit 355cfd6

Please sign in to comment.