【C++】如何刪除指針(鏈表節點)


由於在進行鏈表操作時,尤其是刪除節點時,經常會因為對當前節點進行操作而導致內存或
指針出現問題。有兩個小技巧可以解決這個問題:一是盡量處理當前節點的下一個節點而非當前
節點本身,二是建立一個虛擬節點 (dummy node),使其指向當前鏈表的頭節點,這樣即使原鏈表
所有節點全被刪除,也會有一個 dummy 存在,返回 dummy->next 即可。

刪除鏈表中的某個節點可以這樣寫:

delete pToBeDeleted;
pToBeDeleted = nullptr;

但是這兩句是不可以交換的。stackoverflow中一個說明很形象:

pointer = nullptr; is like removing the ink from a business card. You no longer know where the house is located, at least not from looking at that particular business card. But the house is still there.

delete pointer; is like tearing down the house. The business card still tells you where that house used to be, but if you were to drive there (dereference the pointer), you would see the house was gone. Or worse, maybe they put up a nuclear waste storage facility at that address in the meantime.

所以上面兩句代碼的順序也不可變,不然就會形成某個節點(指針指向的對象)丟失在內存中找不到,delete也刪除不了。

https://stackoverflow.com/questions/31618975/whats-the-difference-between-delete-ing-a-pointer-and-setting-it-to-nullptr

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM