程式語言 - LeetCode - C++ - 19. Remove Nth Node From End of List



參考資訊:
https://www.cnblogs.com/grandyang/p/4606920.html

題目:


方法:
1. 先走訪ListNode n次
2. 剩下的(ListNode.size() - n)就是要刪除的位置,這樣就不用先全部走訪一次後,再算倒數第n個

解答:

/**
 * 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) {
        ListNode* cur = head;
        ListNode* pre = head;

        for (int i = 0; i < n; i++) {
            cur = cur->next;
        }

        if (!cur) {
            return head->next;
        }

        while (cur->next) {
            cur = cur->next;
            pre = pre->next;
        }
        pre->next = pre->next->next;

        return head;
    }
};