【发布时间】:2017-02-08 14:11:13
【问题描述】:
我正在使用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;
有人可以帮我理解问题是什么吗?
【问题讨论】:
-
如果
prev为NULL,您不想尝试将prev->next设置为NULL。另外,如果你删除唯一的节点,你需要将*hd设置为NULL。 -
并且在调用
popFromTop之前需要空检查。 -
与实际问题无关,但为什么要使用列表的尾部作为堆栈的顶部,因为它需要遍历完整列表以进行弹出和推送?那是低效的。使用列表的 head 作为栈顶,这样 push 和 pop 都可以立即访问它而无需任何遍历。
标签: c linked-list stack