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

标签 c

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

/* 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/

相关文章:

c - 子进程和父进程之间的管道通信使用 pipe()

c - 获取结构的用户输入的问题

c++ - 应用程序无法正确启动(0x000007b)

c - void * 到 C 中的 struct *

c - 将 char 数组的内容向左移动一位

c - 如何在不创建变量的情况下将项目添加到结构中

c - C 中的同步回调

无法使用 fgets 将 .txt 文件扫描为灵活的数据结构

python - 如何在 Cython 中测量毫秒级的时间?

c - 该算法(Big-O)的时间复杂度是多少?