【刷题-LeetCode】203. Remove Linked List Elements

  1. Remove Linked List Elements

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() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode *dummy = new ListNode(0, head);
        ListNode *pre = dummy, *cur = head;
        while(cur){
            if(cur->val == val){
                pre->next = cur->next;
                cur = cur->next;
            }else{
                pre = cur;
                cur = cur->next;
            }
        }
        return dummy->next;
    }
};
原文地址:https://www.cnblogs.com/vinnson/p/13303584.html