链表堆栈中的弹出函数导致分段错误 - C [英] Pop Function In Linked List Stack Results in Segmentation Fault- C

查看:31
本文介绍了链表堆栈中的弹出函数导致分段错误 - C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C中的链表创建堆栈.代码如下:

I'm creating a stack using a linked list in C. The code is as follows:

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函数将起作用,但是当堆栈中只有一个值时,会导致分段错误.根据我的调试器,问题出在

The Push function works 100% of the time. The pop function works if there are multiple values in the stack, but results in a segmentation fault when there is a single value in the stack. According to my debugger, the issue is in the popFromTop method with

prev->next=NULL; 

有人可以帮助我了解问题所在吗?

Could someone please help me understand what the issue is?

推荐答案

@DavidSchwartz在评论中已经提到.如果条件添加.

As already mentioned in comments by @DavidSchwartz. Add if condition.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆