Thursday, 19 September 2013

C program for adding and deleting nodes from an ascending order in linked list

C program for adding and deleting nodes from an ascending order in linked
list

I get segmentation fault when I execute the following code. The
segmentation fault occurs only when I add an item in a node whose data is
greater than that of 1st node item.
In this code when I try to add 20 then I encounter a segmentation fault
because 20 is greater than the item in the first node. Why does this occur
and how to prevent this error?
Code:
#include <stdio.h>
struct node
{
int data;
struct node *link;
};
int main()
{
struct node *p;
p = NULL;
add(&p,10);
add(&p,9);
add(&p,1);
add(&p,20);
display(p);
printf("\nNo of elements in Linked List=%d",count(p));
delete(&p,7);
delete(&p,4);
delete(&p,5);
delete(&p,9);
display(p);
printf("\nNo of elements in Linked List=%d",count(p));
}
/* adds a node to an ascending order linked list */
add(struct node **q,int num)
{
struct node *r,*temp=*q;
r = malloc(sizeof(struct node));
r->data = num;
/* If list is empty or if new node is to be inserted before */
if(*q==NULL || (((*q)->data) > num))
{
*q = r;
(*q)->link = temp;
}
else
{
/* traverse the list to search the position to insert the new
node */
while(temp!=NULL)
{
if(temp->data <=num && (temp->link->data > num || temp->link
== NULL))
{
r->link = temp->link;
temp->link = r;
return;
}
temp = temp->link; /* go to next node */
}
}
}
display(struct node *q)
{
printf("\n");
while(q!=NULL)
{
printf("%d ",q->data);
q = q->link;
}
}
count(struct node *q)
{
int c=0;
while(q!=NULL)
{
q = q->link;
c++;
}
return c;
}
delete(struct node **q,int num)
{
struct node *old,*temp;
temp = *q;
while(temp!=NULL)
{
if(temp->data == num)
{
if(temp == *q)
{
*q =temp->link;
free(temp);
return;
}
else
{
old->link = temp->link;
free(temp);
return;
}
}
else
{
old = temp;
temp = temp->link;
}
}
printf("\nElement %d not found",num);
}

No comments:

Post a Comment