C++實現(xiàn)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.
這道移除鏈表元素是鏈表的基本操作之一,沒有太大的難度,就是考察了基本的鏈表遍歷和設置指針的知識點,我們只需定義幾個輔助指針,然后遍歷原鏈表,遇到與給定值相同的元素,將該元素的前后連個節(jié)點連接起來,然后刪除該元素即可,要注意的是還是需要在鏈表開頭加上一個dummy node,具體實現(xiàn)參見代碼如下:
解法一:
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; } };
類似題目:
參考資料:
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
到此這篇關于C++實現(xiàn)LeetCode(203.移除鏈表元素)的文章就介紹到這了,更多相關C++實現(xiàn)移除鏈表元素內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C語言文件操作 fopen, fclose, mkdir詳解
本文給大家詳細介紹了下C語言的文件操作函數(shù)fopen, fclose, mkdir的用法及示例,非常的簡單實用,有需要的小伙伴可以參考下。2016-03-03