简体   繁体   中英

Doubly linked list C++ Delete element

I have problem with deleting first and last element of linked list. When I am trying to delete first element, my code do nothing (when I print a list, deleted element is still there). When I am trying to delete the last one, console shows core dumped.

Here is my code:

void Delete_element(point del, node *elem) {

    struct node *temp = elem;

    if(elem->p.x==del.x && elem->p.y == del.y) {   
        elem=elem->next;
        return;
    } else {
        while(elem->next->next!=NULL) {
            if(elem->next->p.x==del.x && elem->next->p.y==del.y) {
                temp=elem->next;
                elem->next=elem->next->next;
                elem->prev=temp->prev;
                return;
            }

            temp=temp->next;
        }
    }

    if(elem->next->p.x==del.x && elem->next->p.y==del.y) {
        elem->next=NULL;
    }
}

EDIT: After fixes

void Delete_element(point del, node *& elem){
     struct node *temp = elem;
if(elem->p.x==del.x && elem->p.y == del.y){
        temp = elem->next;
        free(elem);
        elem=temp;
    return;
}else{
    while(elem->next->next!=NULL)
    {
        if(elem->next->p.x==del.x && elem->next->p.y==del.y)
        {
            temp=elem->next;
            elem->next=elem->next->next;
            elem->next->prev=elem;
            return;
        }

        elem=elem->next;
    }}
    if(elem->next->p.x==del.x && elem->next->p.y==del.y){
            elem->next=NULL;
            return;
    }

}

Now removing an middle element is broken.

Please help

Firstly, you are not actually deleting anything. You are, however, leaving dangling pointers which result in a memory leak. In each case you should be deleting something. This is why you still see the data instead of garbage or some kind of crash.

Second, you look to have an infinite loop. When you hit your while loop you never change elem so elem->next->next never changes.

Third, why are you deleting elem->next in your while loop? Delete elem to avoid confusion.

EDIT:

You can't change elem like that. Think of elem like an integer or float you pass in. If you want elem to maintain the head change you're going to have to pass in a pointer to elem which ends up being a pointer to a pointer.

I believe you have at least two bugs:

In order to modify the first element you must pass a reference to the first pointer as you intent to modify this pointer. use:

void Delete_element(point del, node *& elem)

Removing an element from the middle seems to be broken. instead of:

elem->prev=temp->prev

you should have:

elem->next->prev=element

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