执行以下代码时出现分段错误。仅当我在数据大于第一个节点项目的数据的节点中添加项目时,才会发生分段错误。
在这段代码中,当我尝试添加 20 时,我遇到了分段错误,因为 20 大于第一个节点中的项目。为什么会发生这种情况以及如何防止此错误?
代码:
#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);
}