如何解决在 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 举报,一经查实,本站将立刻删除。