[LintCode] Remove Linked List Elements 移除链表元素

时间:2022-08-11 12:28:55

Remove all elements from a linked list of integers that have value val.

Have you met this question in a real interview?
Example

Given 1->2->3->3->4->5->3, val = 3, you should return the list as 1->2->4->5

LeetCode上的原题,请参见我之前的博客Remove Linked List Elements

解法一:

class Solution {
public:
/**
* @param head a ListNode
* @param val an integer
* @return a ListNode
*/
ListNode *removeElements(ListNode *head, int val) {
ListNode *dummy = new ListNode(-), *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;
}
};