c - 链表堆栈中的 Pop 函数导致段错误 - C

标签 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;

}

推送功能在 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/

相关文章:

c - Arduino StackArray 不是全局的

c - 进程的虚拟地址空间的哪些部分是可覆盖的?

java - 如何创建 "X"模式?

python - python3中的段错误(C)

析构函数嵌套类的 C++ 显式模板?

java - 使用链表代码实现Queue返回空指针异常

c - 为什么 kfifo.h 充满了#define 语句

c - 如何将 gtk "configure-event"传播到自定义 gtkwidget

c++ - 从指向的对象本身有效地释放指针

c - 缓冲区溢出 - 局部变量在堆栈上的顺序