题目描述
根据输入的数列,经过一系列的入栈、出栈、清空栈操作之后,得到一个输出序列。
输入
先输入数列的长度n。
然后输入n个数字,数字均为整数。
输出
根据输入数列中各个数字的值,作如下处理。
1)如果输入的数字大于0,则入栈;
2)如果输入的数字等于0,则清空栈;
3)如果输入数字小于0,则出栈。其中,负号后接的数字表示要出栈的数字的个数。如果数字超过了栈中数字的实际个数,则不作处理。
最后的输出占2行。
1)第一行是出栈的序列;
2)第二行是最后栈中剩下的序列。
样例输入 Copy
10 1 2 3 -2 4 5 -5 -1 6 7
样例输出 Copy
3 2 5 1 4 6 7
#include <iostream>
#include<stdlib.h>
#include<stdio.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
using namespace std;
typedef int Status;
typedef int SElemType;
typedef struct
{
int *base;
int *top;
int stacksize;
} SqStack;
SqStack S;
Status InitStack(SqStack &S,SElemType n)
{
S.base=new SElemType[n];
if(!S.base)
exit(OVERFLOW);
S.top=S.base;
S.stacksize=n;
return OK;
}
Status Push(SqStack &S, SElemType e)
{
if(S.top-S.base==STACK_INIT_SIZE)
return ERROR;
*S.top++=e;
return OK;
}
Status Pop(SqStack &S, SElemType &e)
{
if(S.top==S.base)
return ERROR;
e=*--S.top;
return OK;
}
Status StackEmpty(SqStack &S)
{
if(S.top==S.base)
return OK;
else
return ERROR;
}
int main()
{
int n,m,flag=0,e;
cin>>n;
int score[n];
InitStack(S,n);
while(n)
{
cin>>m;
if(m>=0)
{
if(m==0)
{
while(!StackEmpty(S))
{
Pop(S,e);
flag--;
}
}
else
{
Push(S,m);
flag++;
}
}
else
{
if(-1*m>flag)
{
n--;
continue;
}
else
{
while(!StackEmpty(S)&&(-1*m)>0)
{
Pop(S,e);
m++;
flag--;
cout<<e<<" ";
}
}
}
n--;
}
cout<<endl;
int i=0;
while(!StackEmpty(S))
{
Pop(S,e);
score[i]=e;
i++;
}
while(i>0)
{
cout<<score[i-1]<<" ";
i--;
}
return 0;
}