程式語言 - 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;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
    int i = 0;
    struct ListNode* cur = head;
    struct ListNode* pre = head;

    for (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;
}