简体   繁体   中英

C++ search for a node in an ordered linked list

Hi I have an ordered linked list using structs. The struct has two elements: string name and int id. I am trying to search for a specific node so I can then print it but I keep getting the "Core Dump (Segmentation fault)" error when I try to run the code.

/*
 * search: Auxiliary function that searches for a specific node in the list.
 */
node* search(node* head, int c){  
    node* aux = head; 
    
    while (aux != NULL && aux->id != c)  
        aux = aux->next;  
    return aux;  
}  

/* 
 * showNode: Prints the information of a specific node (search is done by ID).
 */ 
void showNode(node* head, int c) {
    node* aux = head;
    node* resp;

    if (aux != NULL) {
        resp = search(aux, c);
        if(resp->id == c)
            print(resp);
        else
            printf("Node wasn't found");
    } else {
        printf("Error: Empty list. \n");
    }
}

I see one problem straight away (though there may be others).

Your search function will return NULL if the item cannot be found, yet you blindly go and check if resp->id == c - that's unlikely to end well.

You can fix that reasonably easily, you just have to adjust your check in showNode() :

// Find a node and return it, or nullptr if not found.

node *search(node *curr, int c) {  
    while (curr != nullptr && curr->id < c)  
        curr = curr->next;
    return (curr != nullptr && curr->id == c) ? curr : nullptr;  
} 

// Find a node and print it (or if it couldn't be found).
void showNode(node *head, int c) {
    node *resp = search(head, c);
    if (resp != nullptr) {
        print(resp);
    } else {
        printf("Node wasn't found");
    }
}

You'll see I've made some other changes as well, the complete list is:

  • Using the more modern nullptr rather than NULL ;
  • Removing aux in search() , as the parameter passed in is a copy anyway: you may as well just use that (renamed to curr since it's technically doesn't stay the head any more);
  • Dropping out of the search as soon as we find an element greater than or equal to what we want (since, as you state, it's ordered, and I'm assuming order is ascending - if we're looking for 7 and get to 42 , there's no chance 7 will exist beyond that). Then we just return it if it's equal, or return nullptr if not;
  • Removing the possibility of trying to dereference a nullptr ;
  • Not distinguishing between an item not found in an empty list, and an item not found in a non-empty list (something of dubious value). This allows simplification of the showNode() code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM