gpt4 book ai didi

c - 我试图解决的堆栈实现示例

转载 作者:行者123 更新时间:2023-11-30 19:03:58 26 4
gpt4 key购买 nike

我正在尝试在堆栈上练习一个示例,但我发现打印该示例的答案有点困难。

/* A letter means push and an asterisk means pop in the
following sequence. Give the sequence of values returned by the pop operations
when this sequence of operations is performed on an initially empty LIFO stack.

E A S * Y * Q U E * * * S T * * * I O * N * * *
*/
#include<stdio.h>

char a[40] = "EAS*Y*QUE***ST***IO*N***", s[20], b[30];
int top = -1;

这个是PUSH操作。

void push(char a)
{
int i=0;
if (top >= 24)
printf("Overflow.");
else if (a == '*')
b[i++] = pop();
else
s[++top]= a;
}

这就是 POP 操作。

 void pop()
{
if (top < 0)
printf("Underflow");
else
top--;

return s[top+1];
}

以及主要功能。

void main()
{
int i;
printf("%s\n", a);

for (i=0; i<24; i++)
push(a[i]);

for (i=0; i<24; i++)
printf("%c", b[i]);
}

最佳答案

在您的推送函数中,您将 int i 声明为局部变量。考虑到这一点,您能看到您的行 b[i++]=pop(); 将如何始终计算为 b[0]=pop(); 吗?

编辑:以下是建议的更改。根据 Tim 的建议,您应该将 int i 设为 static 变量。

void push(char a)
{
static int i=0;
if(top>=24)
printf("Overflow.");
else if(a=='*')
b[i++]=pop();
else
s[++top]=a;
}

您还需要使 pop 返回 char 而不是 void

char pop()
{
if(top<0)
printf("Underflow");
else
top--;

return s[top+1];
}

jdoodle

关于c - 我试图解决的堆栈实现示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53213743/

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