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

C++實現(xiàn)LeetCode(237.刪除鏈表的節(jié)點)

 更新時間:2021年08月06日 15:58:36   作者:Grandyang  
這篇文章主要介紹了C++實現(xiàn)LeetCode(237.刪除鏈表的節(jié)點),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下

[LeetCode] 237.Delete Node in a Linked List 刪除鏈表的節(jié)點

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

這道題讓我們刪除鏈表的一個節(jié)點,更通常不同的是,沒有給我們鏈表的起點,只給我們了一個要刪的節(jié)點,跟我們以前遇到的情況不太一樣,我們之前要刪除一個節(jié)點的方法是要有其前一個節(jié)點的位置,然后將其前一個節(jié)點的next連向要刪節(jié)點的下一個,然后delete掉要刪的節(jié)點即可。這道題的處理方法是先把當前節(jié)點的值用下一個節(jié)點的值覆蓋了,然后我們刪除下一個節(jié)點即可,代碼如下:

C++ 解法:

class Solution {
public:
    void deleteNode(ListNode* node) {
        node->val = node->next->val;
        ListNode *tmp = node->next;
        node->next = tmp->next;
        delete tmp;
    }
};

Java 解法:

public class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

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

相關(guān)文章

最新評論