Hi,

I am facing difficulty in removing a node from linked list.

For example I am having four nodes having integers (10) (20) (30) (40).

I need to remove second Node that is 20 from linked list.

What i was trying to do is I am maintaining two pointers to the list, one points to the node which is to be removed and the other one points to the previous node. I am trying to redirect the link part of node to be removed to the link part of previous node. And then assgin a NULL value to the link part of node to be removed, so that it gets seperated from the linked list. but somehow its not working, when i try to print my output , the output also shows the removed node which i dont know why.

Please help.....

This is my code for Remove function in my program.

// This is my basic structure of the program //

struct node

{

int data ;

struct node *link;

};

void remove (struct node **q,int num);

main()

{

struct node *q; // This pointer always points to the first node in the list

(Now please assume that i have added all the nodes 10, 20, 30 and 40 and there respective links )

remove (&p, 20);

}

void remove(struct node **q, int num)

{

  struct node *temp, *old;

  temp=*q;

  while(temp->data==num)

{

  if(temp==*q)

{

  *q=temp->link;

  temp->link=NULL;

}  

  else

{  

  old=temp->link;
  temp->link=NULL;
}  


}


while (temp->data != num)

{

  if(temp=NULL)

{

   printf("Element not found\n");

}   

   else

{

   old=temp;
   temp=temp->link;
} 

}

}

Seems to me you have too many if statements. All you need is something on the order of this: Note: I just write this off the top of my head so it might not be completly correct. It also assumes all the nodes have unique values, there are no duplicates.

oid remove(struct node **q, int num)
{
  struct node *temp, *old;
  old = temp=*q;
  while( temp && temp->data != num)
  {
      old = temp;
      temp = temp->next;
  }
  if( temp != NULL)
  {
      if(temp == *q)
      {
          // delete the first noded in the list?
          *q = temp->next;
      }
      else
      {
          old->next = temp->next;
      }
      free(temp);
  }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.