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
题意:如题。
解法一:
/**
* 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) {
ListNode dummy(0);
ListNode *pre = &dummy, *cur = head, *nex;
dummy.next = head;
while(cur){
nex = cur->next;
if(cur->val == val){
pre->next = nex;
//delete cur;
cur = nex;
}
else{
pre = cur;
cur = nex;
}
}
return dummy.next;
}
};
解法二:递归。
/**
* 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 head;
head->next = removeElements(head->next, val);
return head->val == val ? head->next : head;
}
};