๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 19 - Remove Nth Node From End of List (Medium)

by HandHand 2021. 3. 3.

๋ฌธ์ œ

LeetCode - 19๋ฒˆ

ํ’€์ด ๊ณผ์ •

๋งํฌ๋“œ ๋ฆฌ์ŠคํŠธ์—์„œ ๋’ค์—์„œ n ๋ฒˆ์งธ ๋…ธ๋“œ๋ฅผ ์‚ญ์ œํ•˜๋Š” ์—ฐ์‚ฐ์„ ๊ตฌํ˜„ํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋’ค์—์„œ n ๋ฒˆ์งธ ๋…ธ๋“œ๋ฅผ ์ฐพ๊ธฐ ์œ„ํ•ด์„œ ์šฐ์„  ๋ฆฌ์ŠคํŠธ์˜ ์ „์ฒด ํฌ๊ธฐ๋ฅผ ์•Œ์•„๋‚ธ ๋‹ค์Œ, ์ด๋™ํ•ด์•ผ ํ•˜๋Š” offset ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค.
์ดํ›„ ๋‘ ๊ฐœ์˜ ํฌ์ธํ„ฐ๋ฅผ ํ™œ์šฉํ•ด์„œ next ์†์„ฑ์„ ์žฌ์ง€์ •ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * 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 offset = getSize(head) - n;
  let prev = null;
  let cur = head;

  while (offset > 0) {
    prev = cur;
    cur = cur.next;
    offset--;
  }

  if (prev) {
    prev.next = cur.next;
  } else {
    head = head.next;
  }

  return head;
};

function getSize(head) {
  let size = 1;

  for (let cur = head; cur.next; cur = cur.next) size++;

  return size;
}
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 89 - Gray Code (Medium)  (0) 2021.03.03
LeetCode 118 - Pascal's Triangle (Easy)  (0) 2021.03.03
LeetCode 79 - Word Search (Medium)  (0) 2021.03.03
LeetCode 771 - Jewels and Stones (Easy)  (0) 2021.03.03
LeetCode 5 - Longest Palindromic Substring (Medium)  (0) 2021.03.03

๐Ÿ’ฌ ๋Œ“๊ธ€