此代碼是使用雙鏈接列表堆棧。這個代碼工作正常,除了一個條件,即每當最後一個節點被刪除,它顯示「Segmentation fault」錯誤!顯示錯誤分段錯誤
#include<stdio.h>
#include<stdlib.h>
typedef struct node_type{
int value;
struct node_type *next, *prev;
}node;
node *insert(int value, node *top){
node *p;
p = (node*)malloc(sizeof(node));
if(top == NULL){
top = p;
p -> value = value;
p -> next = NULL;
p -> prev = NULL;
return top;
}
else{
p -> value = value;
p -> next = top;
p -> prev = NULL;
top -> prev = p;
top = p;
return top;
}
}
node *del(node *top){
node *temp;
if(top == NULL){
printf("Stack is empty\n");
}
else{
temp = top;
top = top -> next;
top -> prev = NULL;
free(temp);
}
return top;
}
node *disp(node *top){
if(top == NULL){
printf("Stack is empty\n");
}
else{
while(top != NULL){
printf("The value is: %d\n", top -> value);
top = top->next;
}
}
}
int main(){
int value, ch = 0;
node *top = NULL;
while(ch != 4){
printf("------> 1. Insert <-------\n");
printf("------> 2. Delete <-------\n");
printf("------> 3. Display <-------\n");
printf("------> 4. Exit <-------\n");
printf("Enter the choice\n");
scanf("%d",&ch);
switch(ch){
case 1:
printf("Enter the value\n");
scanf("%d",&value);
top = insert(value, top);
break;
case 2:
printf("Removing the element\n");
top = del(top);
break;
case 3:
disp(top);
break;
case 4:
exit(0);
break;
default:
printf("Wrong Choice\n");
break;
}
}
return 0;
}
具體來說,不要做'top - > prev = NULL;'如果'top'是'NULL'。 –