Think:
就是模拟栈的操作, 注意点时 栈时cnt - 1, 以及 在P操作时 若 为满栈也要 输入数字~~~
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’,否则输出栈顶元素的值,并让其出栈;
每个输出占据一行,每组测试数据(最后一组除外)完成后,输出一个空行。
Example 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
Example Output
E
9
8
F
8
3
5
Hint
建议: 用串的方式(%s)读入操作字符。
#include<bits/stdc++.h>
using namespace std;
typedef int Elemtype;
#define INF 0x3f3f3f
typedef struct
{
Elemtype *top;
Elemtype *base;
int stacksize;
}sqstack;
void Mal(sqstack &L);
void Push(sqstack &L, Elemtype key);
int Gettop(sqstack &L);
int Pop(sqstack &L, Elemtype key);
bool Empty(sqstack &L);
int cnt;
int main()
{
int T;
char key;
int n, m;
int keyword;
cin >> T;
while(T --)
{
cin >> n >> m;
cnt = 0;
sqstack L;
Mal(L);
while(m --)
{
cin >> key;
if (key == 'P')
{
cin >> keyword;
if (cnt == n)
cout << "F" << endl;
else
{
Push(L, keyword);
}
}
if (key == 'A')
{
if(Empty(L) == true)
cout << "E" << endl;
else
Gettop(L);
}
if (key == 'O')
{
if (Empty(L) == true)
cout << "E" << endl;
else
{
int ans = Pop(L, ans);
cout << ans << endl;
cnt --;
}
}
}
if (T)
cout << endl;
}
}
void Mal(sqstack &L)
{
L.base = (Elemtype *)malloc(INF * sizeof(Elemtype));
if (!L.base)
exit(-1);
else
L.top = L.base;
L.stacksize = INF;
}
void Push(sqstack &L, Elemtype key)
{
if(L.top - L.base >= L.stacksize)
{
L.base = (Elemtype *)realloc(L.base, (L.stacksize + 50)*sizeof(Elemtype));
if(!L.base)
{
exit(-1);
}
L.top = L.base + L.stacksize;
L.stacksize += 50;
}
*L.top ++ = key;
cnt ++;
}
int Gettop(sqstack &L)
{
cout << *(L.top - 1) << endl;
return 0;
}
int Pop(sqstack &L, Elemtype key)
{
if (L.top == L.base)
return 0;
else
return key = *(-- L.top);
}
bool Empty(sqstack &L)
{
if (L.top == L.base)
return true;
else
return false;
}