欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++實現(xiàn)LeetCode(19.移除鏈表倒數(shù)第N個節(jié)點)

 更新時間:2021年07月13日 10:45:31   作者:Grandyang  
這篇文章主要介紹了C++實現(xiàn)LeetCode(19.移除鏈表倒數(shù)第N個節(jié)點),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下

[LeetCode] 19. Remove Nth Node From End of List 移除鏈表倒數(shù)第N個節(jié)點

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

這道題讓我們移除鏈表倒數(shù)第N個節(jié)點,限定n一定是有效的,即n不會大于鏈表中的元素總數(shù)。還有題目要求一次遍歷解決問題,那么就得想些比較巧妙的方法了。比如首先要考慮的時,如何找到倒數(shù)第N個節(jié)點,由于只允許一次遍歷,所以不能用一次完整的遍歷來統(tǒng)計鏈表中元素的個數(shù),而是遍歷到對應位置就應該移除了。那么就需要用兩個指針來幫助解題,pre 和 cur 指針。首先 cur 指針先向前走N步,如果此時 cur 指向空,說明N為鏈表的長度,則需要移除的為首元素,那么此時返回 head->next 即可,如果 cur 存在,再繼續(xù)往下走,此時 pre 指針也跟著走,直到 cur 為最后一個元素時停止,此時 pre 指向要移除元素的前一個元素,再修改指針跳過需要移除的元素即可,參見代碼如下:

方式一:

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (!head->next) return NULL;
        ListNode *pre = head, *cur = 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;
    }
};

方式二:

class Solution {
public:
    int getLength(ListNode* head) {
        int length = 0;
        while (head) {
            ++length;
            head = head->next;
        }
        return length;
    }

    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* dummy = new ListNode(0, head);
        int length = getLength(head);
        ListNode* cur = dummy;
        for (int i = 1; i < length - n + 1; ++i) {
            cur = cur->next;
        }
        cur->next = cur->next->next;
        ListNode* ans = dummy->next;
        delete dummy;
        return ans;
    }
};

到此這篇關于C++實現(xiàn)LeetCode(19.移除鏈表倒數(shù)第N個節(jié)點)的文章就介紹到這了,更多相關C++實現(xiàn)移除鏈表倒數(shù)第N個節(jié)點內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論