C++實(shí)現(xiàn)LeetCode(237.刪除鏈表的節(jié)點(diǎn))
[LeetCode] 237.Delete Node in a Linked List 刪除鏈表的節(jié)點(diǎn)
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é)點(diǎn),更通常不同的是,沒有給我們鏈表的起點(diǎn),只給我們了一個要刪的節(jié)點(diǎn),跟我們以前遇到的情況不太一樣,我們之前要刪除一個節(jié)點(diǎn)的方法是要有其前一個節(jié)點(diǎn)的位置,然后將其前一個節(jié)點(diǎn)的next連向要刪節(jié)點(diǎn)的下一個,然后delete掉要刪的節(jié)點(diǎn)即可。這道題的處理方法是先把當(dāng)前節(jié)點(diǎn)的值用下一個節(jié)點(diǎn)的值覆蓋了,然后我們刪除下一個節(jié)點(diǎn)即可,代碼如下:
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++實(shí)現(xiàn)LeetCode(237.刪除鏈表的節(jié)點(diǎn))的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)刪除鏈表的節(jié)點(diǎn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
盤點(diǎn)分析C語言中少見卻強(qiáng)大的字符串函數(shù)
這篇文章主要為大家盤點(diǎn)及分析C語言中少見卻強(qiáng)大的字符串函數(shù),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-02-02
C++?Qt開發(fā)之使用QUdpSocket實(shí)現(xiàn)組播通信
Qt?是一個跨平臺C++圖形界面開發(fā)庫,利用Qt可以快速開發(fā)跨平臺窗體應(yīng)用程序,本文將重點(diǎn)介紹如何運(yùn)用QUdpSocket組件實(shí)現(xiàn)基于UDP的組播通信,感興趣的可以了解下2024-03-03
C++實(shí)現(xiàn)簡單學(xué)生管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)簡單學(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03
舉例講解C語言程序中對二叉樹數(shù)據(jù)結(jié)構(gòu)的各種遍歷方式
這篇文章主要介紹了舉例講解C語言程序中對二叉樹數(shù)據(jù)結(jié)構(gòu)的各種遍歷方式,先序中序后序二叉樹遍歷幾乎成了最老生常談的數(shù)據(jù)結(jié)構(gòu)基礎(chǔ)知識,的朋友可以參考下2016-04-04

