入栈和出栈的基本操作

#include <iostream>
#define MAXSIZE 10000
using namespace std;

typedef struct 
{
	int *base;
	int *top;
	int stacksize;
	
 }SqStack;
 
 int InitStack(SqStack &S)
 {
 	S.base=new int [MAXSIZE];
	if(!S.base) return 0;
 	S.top=S.base;
 	S.stacksize=MAXSIZE;
 	return 1;
 }
 
int Push(SqStack &S,int e)
{
	if(S.top-S.base==S.stacksize)return 0;//cout<<"PUSH ERROR"<<endl;
	*S.top=e;
	S.top++;
	return 1;
}

int GetTop(SqStack S)
{
	if(S.top!=S.base)
		return *(S.top-1);
}

int Pop(SqStack &S,int &e)
{
	if(S.top==S.base)
	{
	//	cout<<"POP ERROR"<<endl;
		return 0;
	}
	//cout<<GetTop(S)<<endl;
	S.top--;
	e=*S.top;
	return 1;
}

int main()
{
	
	int n,a=0;int e=0;int tag=0;
	SqStack S;
	while(1)
	{
		//cout<<"new"<<endl;
		tag=0;
		InitStack(S); 
		cin>>n;
		if(n==0)return 0;
		while(n>0)
		{
			//cout<<"n:"<<n<<endl;
			cin>>a;
			if(a!=-1&&tag==0)Push(S,a);
			else 
			{
				if(tag==0)
				{
					if(Pop(S,e))
					{
						cout<<e<<endl;
					}
					else
					{
						cout<<"POP ERROR"<<endl;
						tag=1;
						//goto X;
					}
				}
				//else cout<<"tag="<<tag<<endl;	
			}
			n--;
		//	cout<<"n:"<<n<<endl;
		}
		//X:int k;
		//if(n==0)cout<<"输入完成!"<<endl; 
	}
	return 0;
}

描述

输入一个整数序列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
发布了100 篇原创文章 · 获赞 4 · 访问量 3689

猜你喜欢

转载自blog.csdn.net/weixin_43673589/article/details/104391830