203 Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.
Example:

Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

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 *dummy = new ListNode(0);
        dummy->next = head;
        ListNode *p = dummy, *tmpp;
        while ( true ) {
            if ( p->next == NULL ) break;
            if ( p->next->val == val ) {
                tmpp = p->next->next;
                p->next = tmpp;
            }
            else p = p->next;
            if ( p == NULL ) break;
        }
        return dummy->next;
    }
};

Notes

  • consecutive duplicates
  • Note the usage of dummy node!
  • Note the NULL pointer!

results matching ""

    No results matching ""