我正在使用 C 中的链表创建堆栈。代码如下:
struct node{
int xposition;
int yposition;
struct node* next;
};
void pushToTop(struct node** hd, int x, int y){
struct node* curr= *hd;
struct node* prev=NULL;
while(curr!=NULL){
prev=curr;
curr= curr->next;
}
struct node* ptr= (struct node*)malloc(sizeof(struct node));
ptr->xposition=x;
ptr->yposition=y;
ptr->next=curr;
if(prev==NULL){
*hd= ptr;}
else{
prev->next=ptr;
}
}
void popFromTop(struct node** hd ){
struct node* curr= *hd;
struct node* prev=NULL;
while ( curr->next !=NULL) {
prev=curr;
curr=curr->next;
}
free(curr);
prev->next= NULL;
}
推送功能在 100% 的时间内都有效。如果堆栈中有多个值,pop 函数会起作用,但当堆栈中只有一个值时,会导致段错误。 根据我的调试器,问题出在带有
的 popFromTop 方法中prev->next=NULL;
有人可以帮助我了解问题所在吗?
最佳答案
正如@DavidSchwartz 在评论中提到的那样。 添加if条件。
void popFromTop(struct node** hd ){
struct node* curr= *hd;
//Base condition to handle empty list
if(*hd == NULL)
return;
struct node* prev=NULL;
while ( curr->next !=NULL) {
prev=curr;
curr=curr->next;
}
free(curr);
if(prev != NULL)
prev->next= NULL;
else
*hd = NULL;
}
关于c - 链表堆栈中的 Pop 函数导致段错误 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39784052/