본문 바로가기
LeetCode

[LeetCode] 19. Remove Nth Node From End of List

by JungSeung 2023. 10. 24.
728x90

https://leetcode.com/

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


Example 1:

출처 : https://leetcode.com/problems/remove-nth-node-from-end-of-list/

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

 

Code :

var removeNthFromEnd = function(head, n) {
    // 새로운 더미 노드를 생성하여 헤드로 설정합니다.
    const root = new ListNode(0);
    root.next = head;
    
    let front = root; // 앞쪽 포인터를 더미 노드로 설정합니다.
    let back = root; // 뒤쪽 포인터를 더미 노드로 설정합니다.
    
    // 주어진 n만큼 뒤쪽 포인터를 이동시킵니다.
    while (n >= 0) {
        front = front.next;
        n--;
    }
    
    // 앞쪽 포인터가 끝에 도달할 때까지 두 포인터를 이동시킵니다.
    while (front) {
        front = front.next;
        back = back.next;
    }

    // 뒤쪽 포인터의 다음 노드를 현재 노드의 다음 노드로 설정하여 노드를 제거합니다.
    back.next = back.next.next;
    return root.next; // 새로운 연결 리스트의 헤드 노드를 반환합니다.
};

 

Solutions Code :

var removeNthFromEnd = function(head, n) {
    let fast = head; // 빠른 포인터를 헤드로 설정합니다.
    let slow = head; // 느린 포인터를 헤드로 설정합니다.
    
    // n만큼 빠른 포인터를 이동시킵니다.
    for (let i = 0; i < n; i++) fast = fast.next;

    // 빠른 포인터가 null이라면 헤드의 다음 노드를 반환합니다.
    if (!fast) return head.next;

    // 빠른 포인터가 끝에 도달할 때까지 두 포인터를 이동시킵니다.
    while (fast.next) {
        fast = fast.next;
        slow = slow.next;
    }

    // 느린 포인터의 다음 노드를 현재 노드의 다음 노드로 설정하여 노드를 제거합니다.
    slow.next = slow.next.next;
    return head; // 수정된 연결 리스트의 헤드 노드를 반환합니다.
};

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 21. Merge Two Sorted Lists  (0) 2023.10.24
[LeetCode] 20. Valid Parentheses  (0) 2023.10.24
[LeetCode] 18. 4Sum  (2) 2023.10.24
[LeetCode] 17. Letter Combinations of a Phone Number  (2) 2023.10.24
[LeetCode] 16. 3Sum Closest  (0) 2023.10.23