c - C中使用函数进行堆栈操作

标签 c function stack

在此程序中,pop 函数没有被执行。

语句“弹出值”未打印在输出中。

当我显示堆栈时,即使在调用 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();
 }

最佳答案

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

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

在这种情况下,如果堆栈为空,则 exception会引发并且不会返回任何内容,但是正如您在 printf 之后所写的那样,您必须在 if 语句中返回一些您没有返回的内容!

而且您的 case2 中也有拼写错误,应该是 case 2

关于c - C中使用函数进行堆栈操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32075588/

相关文章:

python - for in a parameter function python - zip dynamic

谁能解释一下如何从函数返回 C 中的二维数组?

c - 有没有办法保存和恢复C中的调用堆栈

c - kiss_fftr 的 KissFFT 输出

java - USB调试代码

C Unix,pthread_create : fail itself

javascript - 为什么我的功能只是闪烁并带我返回主页?

assembly - sscanf 是如何工作的? ( assembly 中)

c++ - iostream是否占用堆栈空间?

c++ - sscanf 多个输入