在 C 中使用链表错误地实现堆栈数据类型

问题描述

我刚刚开始学习数据结构,我一直在尝试用 C 语言实现它们。在这段 C 代码中,我尝试使用链表实现堆栈。我使用gdb来找出BUG评论。我不知道如何解决这个问题(甚至不知道为什么会出现这个问题)。

#include <stdio.h>
#include <stdlib.h>

// Linked List (As a stack,following LIFO principle)
// Dynamic size
typedef struct node
{
    int number;
    struct node *next;
}
node;

// Prototypes
void push(node *list,int number);
int pop(node *list);
void free_list(node *list);

int main(void)
{
    // Making empty linked list
    node *list = NULL;

    // Adding elements to list
    push(list,1);
    // BUG: Here,the value of list is not changed

    printf("%i\n",list->number);

    // Freeing list
    free_list(list);

    return 0;
}

void push(node *list,int number)
{
    node *temp = malloc(sizeof(node));
    if (temp == NULL)
    {
        puts("Could not allocate memeory for element");
        return;
    }

    temp->number = number;
    temp->next = list;

    list = temp; 
    // BUG: Value getting assigned here
}

int pop(node *list)
{
    if (list == NULL)
        return 0;

    node *temp = list;

    int number = list->number;
    list = list->next;

    free(temp);

    return number;
}

void free_list(node *list)
{
    while (list != NULL)
    {
        node *temp = list->next;
        free(list);
        list = temp;
    }
}

一些帮助将不胜感激!!!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)