Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5
Method 1.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val){
if (head == NULL)
return NULL;
head->next = removeElements(head->next, val);
if (head->val == val)
return head->next;
else
return head;
}
};
Method 2.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (head == NULL)
return NULL;
ListNode* dummy = new ListNode(-1);
dummy->next = head;
ListNode* cur = dummy;
while (cur->next) {
if (cur->next->val == val) {
ListNode* temp = cur->next;
cur->next = temp->next;
temp->next = NULL;
delete temp;
}
else
cur = cur->next;
}
return dummy->next;
}
};