数据结构实验之栈与队列八:栈的基本操作
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic
Problem Description
堆栈是一种基本的数据结构。堆栈具有两种基本操作方式,push 和 pop。push一个值会将其压入栈顶,而 pop 则会将栈顶的值弹出。现在我们就来验证一下堆栈的使用。
Input
首先输入整数t(1 <= t <= 10),代表测试的组数,以后是 t 组输入。
对于每组测试数据,第一行输入两个正整数 m(1 <= m <= 100)、n(1 <= n <= 1000),其中m代表当前栈的最大长度,n代表本组测试下面要输入的操作数。 而后的 n 行,每行的第一个字符可能是’P’或者’O’或者’A’;如果是’P’,后面还会跟着一个整数,表示把这个数据压入堆栈;如果是’O’,表示栈顶元素出栈;如果是’A’,表示询问当前栈顶的值’。
Output
对于每组测试数据,根据其中的命令字符来处理堆栈;
(1)对所有的’P’操作,如果栈满输出’F’,否则完成压栈操作;
(2)对所有的’A’操作,如果栈空,则输出’E’,否则输出当时栈顶的值;
(3)对所有的’O’操作,如果栈空,则输出’E’,否则输出栈顶元素的值,并让其出栈;
每个输出占据一行,每组测试数据(最后一组除外)完成后,输出一个空行。
Sample Input
2
5 10
A
P 9
A
P 6
P 3
P 10
P 8
A
P 2
O
2 5
P 1
P 3
O
P 5
A
Sample Output
E
9
8
F
8
3
5
Hint
建议: 用串的方式(%s)读入操作字符。
#include <iostream>
#include <string>
#include<stdio.h>
#include<stdlib.h>
#define max 10002
using namespace std;
typedef int Elemtype;
typedef struct
{
Elemtype *top;
Elemtype *base;
}Sqstack;
int m;
int l;
void initstack(Sqstack &S)
{
S.base = (Elemtype *)malloc(max *sizeof(Elemtype));
S.top = S.base;
}
void push(Sqstack &S, Elemtype e)
{
*S.top++ = e;
}
Elemtype gettop(Sqstack S)
{
Elemtype e;
e = *(S.top-1);
return e;
}
Elemtype pop(Sqstack &S)
{
Elemtype e;
e = *--S.top;
return e;
}
int emptystack(Sqstack S)
{
if(S.top==S.base)
return 1;
else
return 0;
}
int full(Sqstack S)
{
if(l==m)
return 1;
else
return 0;
}
int main()
{
int t, n, k;
cin>>t;
for(k=0; k<t; k++)
{
cin>>m>>n;
Sqstack S;
initstack(S);
l = 0;
int i;
for(i=0; i<n; i++)
{
char s[5];
scanf("%s", s);
if(s[0]=='P')
{
int x;
scanf("%d", &x);
if(full(S)==1)
{
cout<<'F'<<endl;
}
else
{
push(S, x);
l++;
}
}
else if(s[0]=='A')
{
if(emptystack(S)==1)
cout<<'E'<<endl;
else
{
cout<<gettop(S)<<endl;
}
}
else if(s[0]=='O')
{
if(emptystack(S)==1)
cout<<'E'<<endl;
else
{
cout<<pop(S)<<endl;
l--;
}
}
}
if(k!=t-1)
cout<<endl;
}
return 0;
}
/***************************************************
User name: jk160532姜兴友
Result: Accepted
Take time: 0ms
Take Memory: 236KB
Submit time: 2017-10-16 23:55:08
****************************************************/