Given the
head
of a linked list, remove the n
th
node from the end of the list and return its head.Example 1:

Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1 Output: []
Example 3:
Input: head = [1,2], n = 1 Output: [1]
Constraints:
- The number of nodes in the list is
sz
.
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
풀이
은찬
const removeNthFromEnd = (head, n) => { let current = head; let prev = head; for(let i = 0; i < n; i++){ current = current.next; } if(!current){ return head.next; } while(current.next){ current = current.next; prev = prev.next; } prev.next = prev.next.next; return head; };
재영
/** * 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) { let nodeHead = head; const lists = {}; lists.length = 0; let index = 0; while (true) { lists[index] = nodeHead; nodeHead = nodeHead.next; index += 1; lists.length += 1; if (nodeHead === null) { break; } } const targetIndex = lists.length - n; if (targetIndex === 0) { head = head.next; return head; } lists[targetIndex - 1].next = lists[targetIndex].next; // 연결리스트를 이어줌. return head }; // 56ms, 98% fast