mariia-kornieva
8/16/2019 - 7:54 PM

19. Remove Nth Node From End of List

  1. Remove Nth Node From End of List
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        auto curr = new ListNode(0);
        curr->next = head;
        auto first = curr;
        auto second = curr;
        
        for (int i = 0; i <= n; ++i)
        {
            first = first->next;
        }
        
        while (first)
        {
            first = first->next;
            second = second->next;
        }
        
        second->next = second->next->next;
        
        return curr->next;
    }
};