欢迎登录北京林业大学OJ系统
http://www.bjfuacm.com
243入栈和出栈的基本操作
描述
输入一个整数序列a1,a2,a3…,an。当ai不等于-1时将ai进栈;当ai=-1时,输出栈顶元素并将其出栈。
输入
多组数据,每组数据有两行,第一行为序列的长度n,第二行为n个整数,整数之间用空格分隔。当n=0时输入结束。
输出
对于每一组数据输出若干行。每行为相应的出栈元素。当出栈异常时,输出“POP ERROR”并结束本组数据的输出。
输入样例 1
5
1 2 -1 -1 1
5
1 -1 -1 2 2
0
输出样例 1
2
1
1
POP ERROR
#include<iostream>
using namespace std;
#define MAX 100
#define OK 0
#define ERROR -1
#define OVERFLOW -2
typedef struct
{
int *base;
int *top;
int stacksize;
}SqStack;
int InitSqStack(SqStack &S)
{
S.base=new int[MAX];
if(!S.base) return OVERFLOW;
S.top=S.base;
S.stacksize=MAX;
return OK;
}
int Push(SqStack &S,int e)
{
if(S.top-S.base==S.stacksize)
return ERROR;
*S.top=e;
S.top++;
return OK;
}
int Pop(SqStack &S)
{
if(S.top==S.base)
return ERROR;
S.top--;
return OK;
}
int Top(SqStack S)
{
if(S.top==S.base)
return ERROR;
return *(S.top-1);
}
int main()
{
int n;
while(cin>>n&&n!=0)
{
SqStack S;
InitSqStack(S);
int a[MAX];
for(int j=0;j<n;j++)
cin>>a[j];
for(int i=0;i<n;i++)
{
if(a[i]!=-1)
Push(S,a[i]);
else
{
if(S.top!=S.base)
{
cout<<Top(S)<<endl;
Pop(S);
}
else
{
cout<<"POP ERROR"<<endl;
break;
}
}
}
}
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)