Leetcode/NeetCode

[LinkedList][Medium] 19. Remove Nth Node From End of List

자전거통학 2024. 7. 15. 22:41

Remove Nth Node From End of List - LeetCode

 

리스트가 주어질 때, 뒤에서 n 번째에 해당하는 노드를 삭제 하라.

 

 

먼저 뒤에서 n 번째의 노드를 찾는다. 

slow, fast 포인터를 이용하면 찾을 수 있다. 

이 후, head 처리에 유의하며 해당 노드를 삭제 한다.

 

더보기
ListNode* removeNthFromEnd(ListNode* head, int n) 
{
    ListNode* fast = head;
    ListNode* slow = head;
    ListNode* prev = nullptr;
    int cnt = 0;
    while (fast != nullptr)
    {
        if (cnt >= n)
        {
            prev = slow;
            slow = slow->next;
        }

        fast = fast->next;
        ++cnt;
    }

    if(prev != nullptr)
        prev->next = slow==nullptr ? nullptr : slow->next;
    else 
        head = head->next;

    return head;
}

 

결과