LeetCode Remove Nth Node From End of List (JavaScript)

2025. 11. 17. 20:25·코딩테스트/LeetCode

링크 : https://leetcode.com/problems/remove-nth-node-from-end-of-list/

문제 설명

더보기

Given the head of a linked list, remove the nth 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

문제 풀이

뒤에서 값을 지우기 위해 pointer를 하나 두어 계산

n만큼 head를 이동, 이후 pointer와 head를 같이 head의 마지막까지 이동

위와 같이 이동하면 pointer의 다음은 지워야할 숫자 (즉, 뒤에서 n 번째에 해당하는 숫자가 됨)

1,2,3,4,5 / n = 2인 경우 예시

/**
 * 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 dummy = new ListNode(0, head);
    let pointer = dummy;

    for (let i = 0; i < n; i++) {
        head = head.next;
    }

    while (head) {
        head = head.next;
        pointer = pointer.next;
    }

    pointer.next = pointer.next.next;

    return dummy.next;
};

결론

pointer를 하나 두어 마지막에서 n 번째를 계산하는 로직을 세워야 함.

O(N)의 시간복잡도를 가짐

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode Word Search (JavaScript), DFS  (0) 2025.11.18
LeetCode Generate Parentheses (JavaScript)  (0) 2025.11.17
LeetCode 4Sum (JavaScript)  (0) 2025.11.17
LeetCode Letter Combinations of a Phone Number (JavaScript)  (0) 2025.11.17
LeetCode Container With Most Water (JavaScript)  (0) 2025.11.16
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Word Search (JavaScript), DFS
  • LeetCode Generate Parentheses (JavaScript)
  • LeetCode 4Sum (JavaScript)
  • LeetCode Letter Combinations of a Phone Number (JavaScript)
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (213) N
      • 프론트엔드 (64) N
        • JavaScript (51)
        • HTML (3)
        • React (7) N
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (127) N
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (38) N
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Remove Nth Node From End of List (JavaScript)
상단으로

티스토리툴바