删除链表中的值 - lifengyu360/lifengyu_first_git_test GitHub Wiki

删除链表中等于给定值 val 的所有节点。

class Solution {

public:

ListNode* removeElements(ListNode* head, int val) {
    ListNode *head_new = new ListNode(0);
    head_new->next = head;
    ListNode *pre = head_new;
    ListNode *cur = head;

    ListNode *tmp = NULL;
    while(cur != NULL){
        if (cur->val == val){
            tmp = cur;
            pre->next = cur->next;
            cur = cur->next;
            delete tmp; 
        }else {
            cur = cur->next;
            pre = pre->next;
        }                   
    }

    head = head_new->next;
    return head;
}

};