Looping through linked lists

So basically, what I'm trying to do is going through all the nodes and verify if node.value is <= cost. If it is I need to remove that node and in the end I want to store the nodes that weren't remove in a new struct. I'm not sure how exactly am I suppose to do this.

This struct can be an example:

struct node {
    int value;
    node * next;
}

I'm going through all the nodes and remove only the ones that doen't have the required.

node * verify_money(node * head, int cost)
{

    node * iterator = head;

    while(iterator != NULL){
       if(iterator.value <= cost) {  
           /*remove this node*/
       }
       iterator = iterator.next;
    }

return /*struct without nodes removed/*

}

I want to get the remaining nodes.

Upvotes: 1

Views: 68

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596377

What you are asking for really depends on your requirements, which you did not make clear enough.

If you are expected to modify the input list that is being verified, you can do something like this:

node * verify_money(node * head, int cost)
{
    node * iterator = head;
    node * previous = NULL;

    while (iterator) {
        node *next = iterator->next;

        if (iterator->value <= cost) {
            if (previous) previous->next = next;
            if (head == iterator) head = next;
            delete iterator;
        }
        else
            previous = iterator;

        iterator = next;
    }

    return head;
}

If you are expected to return a new list without modifying the original list, you can do something like this instead:

node * verify_money(node * head, int cost)
{
    node * new_head = NULL;
    node ** new_node = &new_head;

    node * iterator = head;
    while (iterator) {
        if (iterator->value > cost) {  
            *new_node = new node;
            (*new_node)->cost = value;
            (*new_node)->next = NULL;
            new_node = &((*new_node)->next);
        }
        iterator = iterator->next;
    }

    return new_head;
}

Upvotes: 3

Related Questions