removeKFromList | Linked List | Data Structure

CODE

// Singly-linked lists are already defined with this interface:
// template<typename T>
// struct ListNode {
//   ListNode(const T &v) : value(v), next(nullptr) {}
//   T value;
//   ListNode *next;
// };
//
ListNode<int> * removeKFromList(ListNode<int> * l, int k) {
    while(l != NULL && l->value ==k){
        l = l->next;
    }
    ListNode<int> * current = l;
    while(current != NULL && current->next != NULL){
        if(current->next->value == k){
            current->next = current->next->next;
        }else{
            current = current->next;
        }
    }
    return l;
}

EXPLANATION:

while(l != NULL && l->value ==k){
        l = l->next;
    }
 
/*If the linked list starts with one or more of k-value node, we dump all of them in succession; by moving the head to point to the first non-k node.*/
 
/*Then we iterate through the whole linked list*/
 
/*And if a node has the value k, we make its previous node point to the next of the current node.*/
current->next = current->next->next;
 
/*Else, we just move on to the next node*/

Leave a Reply

Your email address will not be published. Required fields are marked *