Generation

generate functionSun, 05 Mar 2023

Remove Linked List Elements

/** * 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) { if(head == NULL) return NULL; while(head->val == val) { if(head->next == NULL) return NULL; else head = head->next; } ListNode* temp = head; while(temp->next!=NULL) { if(temp->next->val == val) temp->next = temp->next->next; else temp = temp->next; } return head; } };

Questions about programming?Chat with your personal AI assistant