203. Remove Linked List Elements

 avatar
user_6283553
c_cpp
a year ago
732 B
2
Indexable
Never
/**
 * 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* ptr=head;
        if(head==NULL){
            return NULL;
        }
        else if(ptr->val==val){
            head=ptr->next;
        }
        while(ptr->next!=NULL){
            if(ptr->next->val==val){
                ptr->next=ptr->next->next;
            }
                ptr=ptr->next;
        }
        return head;
    }
};