leetcode203 C++ 28ms 删除链表中满足条件的节点

/**
 * 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* res = nullptr;
        while(head != nullptr && head->val == val){
            head = head->next;
        }
        res = head;
        ListNode* prev = nullptr;
        while(head != nullptr){
            prev = head;
            while(head->next != nullptr && head->next->val == val){
                head->next = head->next->next;
                prev->next = head->next;
            }
            head = head->next;
        }
        return res;
    }
};