Remove all elements from a linked list of integers that have value val
.
Given 1->2->3->3->4->5->3
, val = 3, you should return the list as 1->2->4->5
LeetCode上的原题,请参见我之前的博客。
解法一:
class Solution {public: /** * @param head a ListNode * @param val an integer * @return a ListNode */ 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; } else { pre = pre->next; } } return dummy->next; }};
解法二:
class Solution {public: /** * @param head a ListNode * @param val an integer * @return a ListNode */ ListNode *removeElements(ListNode *head, int val) { if (!head) return NULL; head->next = removeElements(head->next, val); return head->val == val ? head->next : head; }};
本文转自博客园Grandyang的博客,原文链接:,如需转载请自行联系原博主。