203. Remove Linked List Elements

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

/**
 * 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)
            return head;
        ListNode * Dummy = new ListNode(-1);
        Dummy->next = head;
        
        ListNode * pre = Dummy;
        ListNode * p = head;
        while(p){
            if(p->val != val){
                pre = p;
                p = p->next;
            }
            else{
                pre->next = p->next;
                p = p->next;
            }
        }
        
        return Dummy->next;
        delete Dummy;
        
    }
};

 

posted on 2017-03-04 02:10  123_123  阅读(65)  评论(0编辑  收藏  举报