在此程序中,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/