我尝试解决的Stack实现示例

时间:2018-11-08 18:10:33

标签: 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]);
}

1 个答案:

答案 0 :(得分:1)

在push函数中,您将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