#include<stdio.h>
#include<stdlib.h>
//double linked list
struct node {
int data;
struct node *rnext;
struct node *lnext;
}*first=NULL,*last=NULL;
//double linked list
void insertion() {
struct node *nn=malloc(sizeof(*nn));
printf("enter data to be inserted\n");
scanf("%d",&nn->data);
nn->rnext=NULL;
nn->lnext=last;
if(first == NULL) {
first = nn;
last = nn;
}
else{
last->rnext=nn;
}
last=nn;
}
void display() {
struct node *temp;
if(first==NULL) {
printf("list is empty\n");
return;
}
temp=first;
while(temp!=NULL) {
printf("%d \n",temp->data);
temp=temp->rnext;
}
}
void deletion() {
struct node *temp;
if(first==NULL) {
printf("list is empty\n");
return;
}
temp=first;
first=first->rnext;
first->lnext=NULL;
free(temp);
}
int main() {
int option;
do {
printf("enter option 1.insert\n 2.display\n 3.delete\n 4.exit\n");
scanf("%d",&option);
switch(option) {
case 1:
insertion();
break;
case 2:
display();
break;
case 3:
deletion();
break;
}
} while(option!=4);
}
这是一个为删除和插入双链表中的节点而编写的程序。该程序编译没有错误,但在运行时失败,并在列表中只有一个节点时删除节点时出现分段错误错误。谁能帮忙解决这个分段错误?
以下是该程序的一些示例输出:
./out
enter option 1.insertion
2.display
3.deletion
4.exit
1
enter data to be inserted
11
enter option 1.insertion
2.display
3.deletion
4.exit
2
11
enter option 1.insertion
2.display
3.deletion
4.exit
3
Segmentation fault