leetcode 203. Remove Linked List Elements

题目描述:

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

 

posted @ 2017-06-02 11:06  StrongYaYa  阅读(142)  评论(0编辑  收藏  举报