Wednesday, April 22, 2015

Remove Linked List Elements

Problem:
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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

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 *curr = head;
        // Base case
        while (curr != NULL && curr -> val == val) {
            curr = curr -> next;
            head = curr;
        }
        // Iteration start.
        while (curr != NULL) {
            if (curr -> next != NULL && curr -> next -> val == val)
                curr -> next = curr -> next -> next;
            else
                curr = curr -> next;
        }
        return head;
    }
};

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

No comments:

Post a Comment