leetcode 19. 删除链表的倒数第N个节点

Jun 16, 2020
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (head->next == nullptr) return nullptr;
        auto fast = head;
        for (int i = 0; i <= n; ++i) {
            /*
             * if 1->2->3->4->5 delete 5
             * fast will be null
             * if that's the case return the second node
             */
            if (!fast) {
                auto tmp = head;
                head = head->next;
                delete tmp;
                return head;
            }
            fast = fast->next;
        }
        auto slow = head;
        while(fast) {
            fast = fast->next;
            slow = slow->next;
        }
        auto tmp = slow->next;
        slow->next = slow->next->next;
        delete tmp;
        return head;
    }
};
Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.