c中使用函数的堆栈操作

Stack operation in c using functions

在这个程序中,弹出函数没有被执行。

语句'Popped value'没有打印在输出中。

当我显示堆栈时,我推送的所有元素都会被打印出来,即使在调用 pop 函数之后也是如此。

我需要知道为什么会这样。

#include<stdio.h>

#define MAX 7

int x,st[MAX],i,top=-1;

// Entering the elements into stack
void push()
 {
     if(top>=MAX)
        printf("Stack overflow\n");
      else
      {
        printf("\nEnter element to be pushed: ");
        scanf("%d",&x);
        top++;
        st[top]=x;
      }
 }

//Deleting an element from the stack 
int pop()
 {
    if(top==-1)
       printf("Stack is empty");
    else
    {
      x=st[top];
      top--;
      return(x); 
    }

  }

//Displaying contents of stack
void display()
 {

   if(top<=-1)
    printf("Stack Empty");
   else
   {      
       printf("Stack contents\n");
       for(i=top;i>=0;i--)
       printf("%d\n",st[i]);
   }
} 

int main()
{
    int c,item;
    char ch='y';
    while(ch=='y')
    {
      printf("Enter choice\t");
      printf("1.Push 2.Pop 3.Display 4.Exit \n");
      scanf("%d",&c);
      switch(c)
      {
       case 1:
        push();
         break;
       case2:
         item=pop();
         printf("Popped value %d",item);
         break;
       case 3:
         display();
         break;
       case 4:
         exit(0);
         break; 
       }
     }
    getch();
 }

Return (x) 处于 pop 函数的 else 条件。 如果 top==-1 那么它将通过错误

编写 pop 函数的正确方法(以您的编码风格)如下:

#include <exception>
//Deleting an element from the stack
int pop()
{
    if(top == -1)
       throw exception("Stack is empty");
    else
      return st[top--];
} 

在这种情况下,如果堆栈 为空,则 exception 将引发 ,并且 return 不会引发任何事件,但正如您在 printf 之后所写,您必须 return 在您的 if 语句中添加您没有的内容!!

而且你的 case2 中有错字,应该是 case 2