gpt4 book ai didi

c - 在 C 中遍历堆栈

转载 作者:行者123 更新时间:2023-11-30 16:52:37 28 4
gpt4 key购买 nike

我有一个简单的堆栈,我想使用向上和向下函数在它之间移动。我的 down 函数似乎跳过了一些数字,并且计数不正确,如果我向上移动一位,然后向下移动一位,down 函数返回的值小于该值通过up函数显示。请帮助我在这里缺少什么?

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#define SIZE 4096

typedef struct s_stack
{
int capacity;
int count;
int top;
char *list[SIZE];
} t_stack;

char *up(t_stack *stack)
{
if (stack->count == 0)
return (stack->list[0]);
return (stack->list[stack->count--]);
}

char *down(t_stack *stack)
{
if (stack->count > stack->top)
{
stack->count = stack->top;
return ("");
}
if (stack->count < stack->top)
return (stack->list[stack->count++]);
return ("");
}

void create_stack(t_stack *stack)
{
memset(stack->list, 0, SIZE);
stack->count = -1;
stack->top = -1;
stack->capacity = SIZE;
}

void push(t_stack *stack, char *value)
{
if (stack->top == stack->capacity - 1)
return ;
stack->list[++stack->top] = value;
}

int main()
{
t_stack stack;
create_stack(&stack);
push(&stack, "1");
push(&stack, "2");
push(&stack, "3");
push(&stack, "4");
push(&stack, "5");
push(&stack, "6");
push(&stack, "7");
push(&stack, "8");
push(&stack, "9");
push(&stack, "10");
stack.count = stack.top;
while (1)
{
int ret;
char buf[4];
ret = read(0, buf, 4);
if (buf[0] == 'u')
printf("%s\n", up(&stack));
else if (buf[0] == 'd')
printf("%s\n", down(&stack));
else
break ;
}
return 0;
}

最佳答案

My down function seems to skip some numbers and it doesn't count correctly

down()中,你至少必须删除

    if (stack->count < stack->top)

因为 stack->list[stack->top]stack 中有效的最后一项。

if I move one place up then one place down the down function returns a value less than the value displayed by up function.

可能令人困惑的是 up()down() 显示它们正在远离的值,因此当 up()10 移动到 9 它显示 10,当下面的 down()9 返回到 10 它显示 9

关于c - 在 C 中遍历堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41155520/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com