c - 使用数组实现堆栈
问题描述
我正在尝试用 C 中的数组实现堆栈。但我猜我的推送功能不正确。(也许还有其他一些错误)因为当我运行代码时,它会打印“堆栈为空!” 两次。
我该如何解决这个问题,这个实现逻辑是否正确?
#include <stdio.h>
#define SIZE 10
typedef struct stack
{
int top;
int items[SIZE];
}stack;
void push(int a, stack st)
{
if((st.top + 1) != SIZE)
{
st.top++;
st.items[st.top] = a;
}
else
{
printf("\nStack is full!");
}
}
void pop(stack st)
{
if(st.top != -1)
{
st.top--;
}
else
{
printf("\nStack is empty!");
}
}
void printList(stack st)
{
int i;
for(i = 0; i < st.top + 1; i++)
{
printf("%d -> ", st.items[i]);
}
puts("");
}
int main(void)
{
stack stack1;
stack1.top = -1;
stack stack2;
stack2.top = -1;
push(3, stack1);
push(5, stack1);
push(7, stack1);
printList(stack1);
pop(stack1);
printList(stack1);
pop(stack1);
printList(stack1);
}
解决方案
嗨,您的堆栈实现是错误的。使用 gdb 您可以验证这一点。您将结构作为值传递,您应该将其作为地址传递。
在 gdb 上你可以看到
在主 gdb) p &stack1 $4 = (stack *) 0x7fffffffddf0
在推 fn
(gdb) p &st $3 = (堆栈 *) 0x7fffffffdd90
两者都是不同的。
正确的代码如下。
#include <stdio.h>
#define SIZE 10
typedef struct stack
{
int top;
int items[SIZE];
}stack;
void push(int a, stack *st)
{
if((st->top + 1) != SIZE)
{
st->top++;
st->items[st->top] = a;
}
else
{
printf("\nStack is full!");
}
}
void pop(stack *st)
{
if(st->top != -1)
{
st->top--;
}
else
{
printf("\nStack is empty!");
}
}
void printList(stack *st)
{
int i;
for(i = 0; i < st->top + 1; i++)
{
printf("%d -> ", st->items[i]);
}
puts("");
}
int main(void)
{
stack stack1;
stack1.top = -1;
stack stack2;
stack2.top = -1;
push(3, &stack1);
push(5, &stack1);
push(7, &stack1);
printList(&stack1);
pop(&stack1);
printList(&stack1);
pop(&stack1);
printList(&stack1);
}
推荐阅读
- gitlab - 与 gitlab 集成时无法访问 SonarQube 服务器
- macos - 由于白色突出显示,Mac 上的 Lyx 数学无法读取
- python - 如何通过检查 2 列的交集来组合集合的数据框
- vue.js - 如何使库在 Composition API 中全局可用?
- javascript - 为什么我在同时执行多个请求时收到此队列并停滞时间
- amazon-cloudformation - ECS TaskDefinition 创建失败,并显示“提供的请求无效:创建 TaskDefinition:未知卷 'null'”。
- r - 在表中显示事后 Tukey 分析的问题
- fortran - fortran 代码适用于真正的 4,但不适用于真正的 16
- string - 如何让字符串取负索引而不报错
- mysql - mysqldump:得到错误:1356:使用 MySQL Workbench/命令行