Remove Linked List Elements leetcode

C++ Solution to Remove Linked List Elements on LeetCode

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

Explanation

  1. Define the ListNode structure for the singly-linked list.

  2. Create a class Solution for the removeElements function.

  3. Initialize a dummy node with value 0 and set its next pointer to the head of the linked list.

  4. Initialize a pointer current to point to the dummy node.

  5. Iterate through the linked list using a while loop.

  6. Inside the loop, check if the value of the next node is equal to the given value.

  7. If it is, update the pointers to remove the node and free the memory.

  8. If the value is not equal, move the current pointer to the next node.

  9. Return the next pointer of the dummy node, which will be the head of the modified linked list.