简体   繁体   中英

Deleting a node in an ordered linked list in C++

I am working on an ordered linked list in C++. The task is to delete notes from the list and I've got two methods / functions to do that.

/*
 * delete_head: Auxiliary function that deletes the first node of the list.
*/
book *delete_head(book*& deleteNode){
    head = deleteNode->next;
    delete deleteNode;
    
    return head;
} 

/*
 * delete_node: Method that deletes a node from the list. 
 */
 void delete_node(int c){
     book *aux = head;
     
     // Verify list isn't empty.
     if (head != NULL){
         // Case 1: the head should be deleted.
         if (aux->code == c){
             head = delete_head(head);
         } else {
             book *aux2 = head->next;
             while (aux2 != nullptr && aux2->code < c){
                 aux = aux2;
                 aux2 = aux2->next;
             } 
             // Case 2: node wasn't found.
             if (aux2 == NULL){
                 printf("Error: Node doesn't exist. \n");
             } else {
                 // Case 3: the tail should be removed.
                 if (aux2->next == NULL){
                     aux->next = NULL;
                     delete aux2;
                 } else {
                     // Case 4: A node from the middle should be removed.
                     aux->next = aux2->next;
                     delete aux2;
                 } 
             } 
         } 
     } else {
         printf("Error: Empty list. \n");
     } 
 } 

I've tested the code and the cases in which I delete the tail of the list or a node that's in the middle do work. The one that's giving me a bit of trouble is the case in which I need to delete the head and I'm not sure if it's related to the way pointers are handled.

Your helper function is borked:

book *delete_head(book*& deleteNode){
    head = deleteNode->next;
    delete deleteNode;
    
    return head;
} 

You call it with head = delete_head(head);, but when you do that deleteNode is set to a reference to the pointer to head. This means that anything you do to deleteNode you also do to head - and vice versa.

This means that here: delete deleteNode; you delete both deleteNode and head , which is a bit of a problem as you then return head .

Change the function to book *delete_head(book* deleteNode){ and it should do what you want.

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