delete a node in linked list using pointers

4273 views c
4

I'm trying to write a method that gets a linked list (**pplist) and an address to the item I want to delete (*pplaneToDelete). this is what I wrote and the program crashes. any help?

void DeleteAirplane(plane **pplist, plane *pplaneToDelete) {
plane *cur = pplist, *prev = NULL;

if (cur = pplaneToDelete) {

    pplist =cur->next_plane;
    free(cur);
}
while ((cur != pplaneToDelete) && (cur != NULL)) {
    prev = cur;
    cur = cur->next_plane;
}
if (cur != NULL) {
    prev->next_plane = cur->next_plane;
    free(cur);
}
}

answered question

(cur = pplaneToDelete) is assignment not comparison. You should use (cur == pplaneToDelete) Also plane *cur = pplist should be plane *cur = *pplist and pplist =cur->next_plane; should be *pplist =cur->next_plane;.

@kiranBiradar tnx for the comment. can you please explain your tow last arguments? i dont fully understand

1 Answer

8

Few problems here.

  1. (cur = pplaneToDelete) is assignment not comparison hence change it to (cur == pplaneToDelete).

  2. pplist is pointer to pointer, hence you need to de-reference it to get the pointer object it is holding.

    plane *cur = pplist --> plane *cur = *pplist

    pplist =cur->next_plane; --->*pplist =cur->next_plane;

  3. You need to return after deleting head node, otherwise you will invoke undefined behavior trying to access cur pointer.

    if (cur == pplaneToDelete) { *pplist =cur->next_plane; free(cur); return; // Node deleted now return. }

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories