C++實現(xiàn)LeetCode(237.刪除鏈表的節(jié)點)
[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é)點即可。這道題的處理方法是先把當(dāng)前節(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)文章
Cocos2d-x學(xué)習(xí)筆記之Hello World源碼分析
這篇文章主要介紹了Cocos2d-x學(xué)習(xí)筆記之Hello World源碼分析,接上一篇內(nèi)容,本文著重分析源碼文件,需要的朋友可以參考下2014-09-09C++ 多態(tài)性虛函數(shù)和動態(tài)綁定學(xué)習(xí)筆記
這篇文章主要為大家介紹了C++ 多態(tài)性虛函數(shù)和動態(tài)綁定學(xué)習(xí)筆記,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10Cocos2d-x學(xué)習(xí)筆記之開發(fā)環(huán)境搭建
這篇文章主要介紹了Cocos2d-x學(xué)習(xí)筆記之開發(fā)環(huán)境搭建,本文使用Visual Studio作為開發(fā)IDE,是不同于其它教程的,需要的朋友可以參考下2014-09-09

C語言驅(qū)動開發(fā)之內(nèi)核通過PEB獲取進程參數(shù)

解決C++ openCV無法讀取視頻但是可以讀取圖像的問題記錄