0

I made (with a little help) a single linked list, with C++, which sorts entered elements from least to greatest. I want to delete several elements from the same value, but the Delete method I use seems to be able to delete only one, when the code seems to delete more. I try using a loop calling the Delete method in order to delete several elements, and when it deletes one it becomes a segmentation fault. I'd appreciate some help. Thank you.

void List::Append(float time, char type, int cell, long id) {

// Create a new node
Node* newNode = new Node();
newNode->SetTime(time);
newNode->SetType(type);
newNode->SetCell(cell);
newNode->SetId(id);
newNode->SetNext(NULL);

// Create a temp pointer
Node *tmp = head;

if ( tmp ) {
    if ( tmp->Time() < newNode->Time() ) {
        newNode->SetNext(tmp);
        head = newNode;
    }
    else {
        // Nodes already present in the list
        // Parse to end of list anytime the next data has lower value
        while ( tmp->Next() && tmp->Next()->Time() >= newNode->Time() ) {
            tmp = tmp->Next();
        }

        // Point the lower value node to the new node
        Node* _next = tmp->Next();
        tmp->SetNext(newNode);
        newNode->SetNext(_next);
    }
}
else {
    // First node in the list
    head = newNode;
}

}

void List::Delete(long id) {

// Create a temp pointer
Node *tmp = head;

// No nodes
if ( tmp == NULL )
    return;

// Last node of the list
if ( tmp->Next() == NULL ) {
    delete tmp;
    head = NULL;
}
else {
    // Parse thru the nodes
    Node *prev;
    do {
        if ( tmp->Id() == id ) break;
        prev = tmp;
        tmp = tmp->Next();
    } while ( tmp != NULL );

    // Adjust the pointers
    prev->SetNext(tmp->Next());

    // Delete the current node
    delete tmp;
}

}

forkfork
  • 415
  • 6
  • 22
  • @WhozCraig I intended to delete an item when it matches the id I'm looking for, and then I included it inside a loop until it deletes all the same ids. – forkfork Oct 08 '12 at 03:02

1 Answers1

0

in List::Delete code:

 if ( tmp->Id() == id ) break;<--------

if you break, the do{}while loop ends. resulting in only 1 deletion.