C++實現LeetCode(203.移除鏈表元素)
[LeetCode] 203.Remove Linked List Elements 移除鏈表元素
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
這道移除鏈表元素是鏈表的基本操作之一,沒有太大的難度,就是考察瞭基本的鏈表遍歷和設置指針的知識點,我們隻需定義幾個輔助指針,然後遍歷原鏈表,遇到與給定值相同的元素,將該元素的前後連個節點連接起來,然後刪除該元素即可,要註意的是還是需要在鏈表開頭加上一個dummy node,具體實現參見代碼如下:
解法一:
class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode *dummy = new ListNode(-1), *pre = dummy; dummy->next = head; while (pre->next) { if (pre->next->val == val) { ListNode *t = pre->next; pre->next = t->next; t->next = NULL; delete t; } else { pre = pre->next; } } return dummy->next; } };
如果隻是為瞭通過OJ,不用寫的那麼嚴格的話,下面這種方法更加簡潔,當判斷下一個結點的值跟給定值相同的話,直接跳過下一個結點,將next指向下下一個結點,而根本不斷開下一個結點的next,更不用刪除下一個結點瞭。最後還要驗證頭結點是否需要刪除,要的話直接返回下一個結點,參見代碼如下:
解法二:
class Solution { public: ListNode* removeElements(ListNode* head, int val) { if (!head) return NULL; ListNode *cur = head; while (cur->next) { if (cur->next->val == val) cur->next = cur->next->next; else cur = cur->next; } return head->val == val ? head->next : head; } };
我們也可以用遞歸來解,寫法很簡潔,通過遞歸調用到鏈表末尾,然後回來,需要要刪的元素,將鏈表next指針指向下一個元素即可:
解法三:
class Solution { public: ListNode* removeElements(ListNode* head, int val) { if (!head) return NULL; head->next = removeElements(head->next, val); return head->val == val ? head->next : head; } };
類似題目:
Remove Element
Delete Node in a Linked List
參考資料:
https://leetcode.com/problems/remove-linked-list-elements/
https://leetcode.com/problems/remove-linked-list-elements/discuss/57324/AC-Java-solution
https://leetcode.com/problems/remove-linked-list-elements/discuss/57306/3-line-recursive-solution
https://leetcode.com/problems/remove-linked-list-elements/discuss/57331/Accepted-7-line-clean-java-solution
到此這篇關於C++實現LeetCode(203.移除鏈表元素)的文章就介紹到這瞭,更多相關C++實現移除鏈表元素內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- C++實現LeetCode(148.鏈表排序)
- C++實現LeetCode(25.每k個一組翻轉鏈表)
- C++實現LeetCode(147.鏈表插入排序)
- C++實現LeetCode(141.單鏈表中的環)
- C++實現LeetCode(160.求兩個鏈表的交點)