#include<stdio.h>
#include<malloc.h>
typedef struct nnode
{
int value;
struct nnode *next;
} node;
void insert(node **ptr, int val) //for insertion
{
node *temp, *temp2;
temp = *ptr;
if (*ptr == NULL)//if list is empty
{
temp = (node *) malloc(sizeof (node));
temp->value = val;
temp->next = NULL;
*ptr = temp;
}
else
{
while (temp->next != NULL)
{
temp = temp->next;
}
temp2 = (node *) malloc(sizeof (node));
temp2->value = val;
temp2->next = NULL;
temp->next = temp2;
}
}
void display_node(node **ptr)
{
node *temp;
temp = *ptr;
while (temp != NULL)
{
printf("%d--->", temp->value);
temp = temp->next;
}
printf("null");
}
void de_node(node **ptr)
{
int val;
node *temp, *temp2;
temp = *ptr;
temp2 = temp->next;
printf("nenter the value to be deletedn");
scanf("%d", &val);
if ((*ptr) == NULL)
{
printf("list is empty .....");
return;
}
else if ((*ptr)->value == val)
{
*ptr = (*ptr)->next;
free(temp);
}
else
{
while ((temp->next->value != val)&&(temp2->next != NULL))
{
temp = temp->next;
temp2 = temp->next;
}
if (temp2->next == NULL)
{
printf("nvalue not found");
}
if (temp->next->value == val)
{
temp->next = temp2->next;
free(temp2);
}
}
}
void main()
{
node *head = NULL;
int ch;
int n;
while (1)
{
printf("nenter your choicen");
printf("1.ADD ELEMENTn");
printf("2.DELETE ELEMENTn");
printf("3.DISPLAY LISTn");
printf("4.EXITn");
scanf("%d", &ch);
switch (ch)
{
case 1:printf("n enter data n");
scanf("%d", &n);
insert(&head, n);
display_node(&head);
break;
case 2:de_node(&head);
display_node(&head);
break;
case 3:display_node(&head);
break;
case 4:exit(0);
}
}
}
我的问题是之前插入任何东西在列表当我删除元素
例如,当我试图删除一个元素时,列表为空
然后根据我的代码,它应该打印"list is empty....."但是它却给出了分割错误。
问题就在这里:
temp = *ptr;
temp2 = temp->next;
您已将temp
设置为*ptr
,但尚未检查*ptr
是否为NULL。因此,当您尝试用temp->next
解除引用它时,您会得到段错误。
由于您稍后才使用temp2
,因此将这一行移动到while
循环之前:
temp2 = temp->next;