본문 바로가기

알고리즘

Remove Nth Node From End of List - leetcode

var removeNthFromEnd = function (head, n) {
    // Two pointers - fast and slow
    let slow = head;
    let fast = head;
    // Move fast pointer n steps ahead
    for (let i = 0; i < n; i++) {
        if (fast.next === null) {
            // If n is equal to the number of nodes, delete the head node
            if (i === n - 1) {
                head = head.next;
            }
            return head;
        }
        fast = fast.next;
    }
    // Loop until we reach to the end.
    // Now we will move both fast and slow pointers
    while (fast.next !== null) {
        slow = slow.next;
        fast = fast.next;
    }
    // Delink the nth node from last
    if (slow.next !== null) {
        slow.next = slow.next.next;
    }
    return head;
};

function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}

연결된 엘리먼트들은 노드 혹은 버텍스 라고 부른다.

head: linked list의 출입문, 제일 첫 번째로 접근할 수는 노드이며

fast 포인터는 slow 포인터 보다 n 스텝 먼저 움직인다.

 

'알고리즘' 카테고리의 다른 글

OddOccurrencesInArray_Codility  (0) 2022.02.16
CyclicRotation_Codility  (0) 2022.02.15
Valid Anagram - leetcode  (0) 2021.10.08
Single Number - XOR 연산자  (0) 2021.09.27
Best Time to Buy and Sell Stock II  (0) 2021.09.09