🔒 문제 (LeetCode 19)

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

Constraints:

  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

Follow up: Could you do this in one pass?

 

🌊 입출력

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]

 


 

🔑 해결

🌌 알고리즘 - two pointers

fast로 n번째 노드를 찾은 후, fast가 마지막 노드에 도달할 때까지 slow와 함께 한 칸씩 이동하면 결국 slow는 마지막에서 n번째 노드에 도달하게 된다.

/**
 * 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 fast = head, slow = head;
    for(let i = 0; i < n; i++) {
        fast = fast.next;
    }
    
    if(!fast) return head.next;
    
    while(fast.next) {
        fast = fast.next;
        slow = slow.next;
    }
    slow.next = slow.next.next;
    
    return head;
};

 

'코딩테스트 (JS) > 투포인터' 카테고리의 다른 글

[JS] Permutation in String  (0) 2022.07.29
[JS] Longest Substring Without Repeating Characters  (0) 2022.07.29
[JS] Middle of the Linked List  (0) 2022.07.29
[JS] Reverse Words in a String III  (0) 2022.07.29
[JS] Reverse String  (0) 2022.07.29

+ Recent posts