由于逻辑错误,我的代码无法正确执行

时间:2019-01-31 17:43:41

标签: stack runtime-error c++14

我正在研究一个程序来学习堆栈数组的概念。我遇到一个错误,显示堆栈未正确显示[display()函数]。我要去哪里错了?

我尝试检查两次代码。它不会显示display()的输出

#include <iostream>
#include <conio.h>
#include <process.h>

using namespace std;
const int size =50;
int pop(int [] ,int&);
int push(int [] ,int , int);
void display(int [] ,int);
int main()
{
    int s[size],item,top=-1,res;
    char ch='y';
while (ch=='y'||ch=='Y')
{
    cout<<"\n Enter the item for insertion: ";
    cin>>item;
    res=push(s,top,item);
    if(res==-1)
    {
        cout<<"\nOVERFLOW!!!";
        system("pause");
        exit(1);
    }
    cout<<"\nThe stack is :"<<endl;
    display(s,top);
    cout<<"More elements??";
    cin>>ch;
}
cout<<"Now deletion begins\n";
ch='y';
while(ch=='y'||ch=='Y')
{
    res=pop(s,top);
    if(res==-1)
    {
        cout<<"UNDERFLOW!!";
        system("pause");
        exit(1);
    }
    else
    {
        cout<<"\nElement deleted is: "<<res<<endl;
        cout<<"\n The stack now is: "<<endl;
        display(s,top);
    }
    cout<<"delete elements??";
    cin>>ch;
}
getch();
return 0;
}

int push(int s[],int top,int ele)
{
if(top==size-1) return-1;
else
{
    top++;
     s[top]=ele;
}
return 0;
}
int pop (int s[],int &top)
{
int ret;
if(top==-1) return -1;
else 
{
    ret=s[top];
    top--;
}
return ret;
}

void display (int s[], int top)
{
if(top==-1) return;
cout<< s[top]<<"<--"<<endl;
for(int i=top-1;i>=0;i--)
    {
        cout<<s[i]<<endl;
    }
}

display()函数应以堆栈形式显示数组元素。

0 个答案:

没有答案