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

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

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

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

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

方式一:

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

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

相關(guān)文章

最新評(píng)論