Leetcode 203 Solution

This article provides solution to leetcode question 203 (remove-linked-list-elements)

https://leetcode.com/problems/remove-linked-list-elements

Solution

/**
 * 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 dummynode(0);
        dummynode.next = head;
        ListNode* prev = &dummynode;
        ListNode* p = head;

        while (p)
        {
            if (p->val == val)
            {
                prev->next = p->next;
                p = prev->next;
            }
            else
            {
                prev = p;
                p = p->next;
            }
        }

        return dummynode.next;
    }
};