[英]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. 在此代码中,当我尝试添加20时,我遇到了分段错误,因为20大于第一个节点中的项目。 Why does this occur and how to prevent this error? 为什么会发生这种情况,以及如何防止此错误?
#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);
}
In your add
method try changing the line: 在您的add
方法中尝试更改行:
if(temp->data <=num && (temp->link->data > num || temp->link == NULL))
to 至
if(temp->data <=num && (temp->link == NULL || temp->link->data > num))
Since C is short cutting boolean expressions, NULL check will be evaluated before the other operator and stop execution when true. 由于C是捷径布尔表达式,因此将在其他运算符之前评估NULL检查,并在true时停止执行。
Change the line 换线
if(temp->data <=num && (temp->link->data > num || temp->link == NULL))
into 进入
if(temp->data <=num && (temp->link == NULL || temp->link->data > num))
That should solve your problem (it will not try to access data from a node that does not exist) 那应该可以解决您的问题(它不会尝试从不存在的节点访问数据)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.