알고리즘/leetcode

19. Remove Nth Node From End of List

유이얼 2022. 7. 24. 01:53
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        auto cur = head;
        while (n - 1) {
            cur = cur->next;
            --n;
        }
        
        auto prev = &head;
        while (cur->next) {
            cur = cur->next;
            prev = &(*prev)->next;
        }
        
        *prev = (*prev)->next;
        return head;
    }
};

https://youtu.be/o8NPllzkFhE?t=867