Skip to content

[Leetcode] 19. Remove Nth Node From End of List โ€‹

Problem โ€‹

๋ฌธ์ œ ๋งํฌ

๋งํฌ๋“œ๋ฆฌ์ŠคํŠธ์˜ head๊ฐ€ ์ฃผ์›Œ์ง€๊ณ  head๋กœ๋ถ€ํ„ฐ n๋ฒˆ์งธ ๋…ธ๋“œ๋ฅผ ์ œ๊ฑฐํ•˜๋Š” ๋ฌธ์ œ

Solution โ€‹

  1. ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด ์ฃผ์–ด์ง„ ListNode์˜ ๊นŠ์ด๋ฅผ ํŒŒ์•…ํ•œ๋‹ค.
  2. ๊นŠ์ด๋ฅผ ์ด์šฉํ•ด์„œ ์ œ๊ฑฐํ•  ๋ฐ”๋กœ ์•ž๊นŒ์ง€ ์ด๋™ํ•œ๋‹ค.
  3. ์ œ๊ฑฐํ•˜๊ณ ์ž ํ•˜๋Š” ๋…ธ๋“œ๋ฅผ ๊ฑด๋„ˆ๋›ฐ๊ณ  ์ œ๊ฑฐํ•  ๋…ธ๋“œ๊ฐ€ ๊ฐ€๋ฅดํ‚ค๋Š” ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฅดํ‚ค๋„๋ก ๋งŒ๋“ ๋‹ค.

JS CODE โ€‹

javascript
/**
 * 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) {
  const getSize = (node) => {
    if (!node) return 0
    return getSize(node.next) + 1
  }

  let nodeSize = getSize(head)

  let header = new ListNode(),
    temp = null
  header.next = head
  temp = header

  while (temp?.next) {
    if (nodeSize-- === n) {
      temp.next = temp.next.next
    }

    temp = temp.next
  }

  return header.next
}