203. Remove Linked List Elements

 avatar
user_6283553
c_cpp
2 years ago
732 B
5
Indexable
/**
 * 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;
    }
};
Editor is loading...