Search code examples
c++linked-listcircular-list

Deleting a node in circular linked list


I have a basic linked list problem that I have attempted to solve below. I would appreciate any inputs on my approach, correctness of the algorithm (and even coding style). The problem calls for a function that deletes all occurrences of an int in a circular linked list and returns any node from the list or NULL (when the list is null).

Here's some C++ code that I have so far:

struct Node{
    Node* next;
    int data;
};

Node* deleteNode(Node* &node, int num){

    if(!node){
        return NULL;
    }

    Node* given = node;
    Node* del;

    while(node->next != given){
        if(node->next->data == num){
            del = node->next;
            node->next = node->next->next;
            delete del;
        }
        node = node->next;
    }

    //Check if the first node needs to be deleted, with variable node pointing to last element
    if(given->data == num){
        node->next = given->next;
        delete given;
    }

    return node;
}

Solution

  • The delete node; should be delete del;.

    Also, use Node* node as parameter, instead of Node* &node which will prevent non-lvalues from passing in.

    p.s. Forgot a semicolon after struct definition? :)