Movart
Movart

Reputation: 151

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

Upvotes: 0

Views: 638

Answers (2)

ishamdo
ishamdo

Reputation: 86

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

Upvotes: 0

soulsabr
soulsabr

Reputation: 904

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.

Upvotes: 1

Related Questions