链接列表堆栈中的弹出功能导致分段故障-C

时间:2016-09-30 05:06:17

标签: c linked-list stack

我正在使用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;

}

Push功能100%的工作时间。如果堆栈中有多个值,则pop函数有效,但如果堆栈中存在单个值,则会导致分段错误。 根据我的调试器,问题在于使用

的popFromTop方法
prev->next=NULL; 

有人可以帮我理解这个问题是什么吗?

2 个答案:

答案 0 :(得分:4)

正如@DavidSchwartz在评论中已经提到的那样。 添加条件。

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;

}

答案 1 :(得分:1)

如果只有一个节点,则pop()prev->next = NULL始终为NULL。所以在curr之前加上一个条件。

还有一个错误:如果有0个节点,package test在pop()中也是NULL,所以你可能也想处理它。

相关问题