Hobowpen
Hobowpen

Reputation: 71

Trying to delete an element from a double linked list in c

Ι have a problem while trying to delete an element from a double linked list in c.

Nodes_t *remove_Nodes (Nodes_t *a, Nodes_t b){
    Nodes_t *head;
    head=a;
    if ((a->i_pos==b.i_pos) && (a->j_pos==b.j_pos)){
        if (a->next=NULL){
            return NULL;
            }
        else {
            head=a->next;
            head->previous=NULL;
            return head;
            }
        }
    else if ((a->i_pos!=b.i_pos) || (a->j_pos!=b.j_pos)){
        while ((a->next->i_pos!=b.i_pos)||(a->next->j_pos!=b.j_pos)){
            a=a->next;
            if (a->next=NULL){
                return head;
                }
            }
        a=a->next;
        a->previous->next=a->next;
        if (a->next=NULL){
            return head;
            }
        else if (a->next!=NULL){
            a->next->previous=a->previous;
            return head;
            }               
        }
        return head;        
    }

It gets a double linked list, finds an element of type Nodes_t and then deletes it. Although, as I have checked the list and its pointers work fine, when I try to call the function to delete my first element I get a seg fault.

More specifically, as I have checked, the function proceeds just fine until it gets to this point

else {
            head=a->next;
            head->previous=NULL;// HERE 
            return head;
            }

The struct I use is this

typedef struct Nodes {
char    position;
int     i_pos, j_pos;
int     g_distance;
int     h_distance;
int     F_estim;
struct Nodes    *parent;
struct Nodes    *next;
struct Nodes    *previous;

}Nodes_t;

Upvotes: 1

Views: 643

Answers (1)

lxop
lxop

Reputation: 8615

You have used an assignment = instead of a comparison == here:

if (a->next=NULL){

Which will evaluate to NULL, which is false, so will go to your else clause, where you do

head=a->next;
head->previous=NULL;

So head becomes NULL, then you are trying to dereference a NULL pointer to get its previous member.

  • Quick fix: Add the missing = to the first line I quoted.
  • Better fix: Refactor your code. It is too long and has unnecessary bits. And don't forget to check your equals operations.

Upvotes: 3

Related Questions