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; } };
類似題目:
參考資料:
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