Code
#include <stdio.h>
#include <string.h>
int main()
{
int t,stack[1000];
char act[10];
while(~scanf("%d",&t))
{
int k = 0;
while(t--)
{
scanf("%s",act);
if(strcmp(act,"push") == 0)
{
scanf("%d",&stack[k++]);
}
if(strcmp(act,"pop") == 0)
{
if(k < 1)
{
printf("error\n");
}
else
{
k--;
}
}
if(strcmp(act,"top") == 0)
{
if(k == 0)
printf("empty\n");
else
printf("%d\n",stack[k-1]);
}
}
printf("\n");
}
return 0;
}
反思:字符串练习,用一个stack数组模拟栈结构,用strcmp()函数判断操作,用k模拟栈的top指针。
更新:大二学习了数据结构,试着用了C++STL的stack实现。注意每次读入n后要清空栈。
Code - C++
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
int n, num;
string op;
stack <int> S;
while(cin >> n)
{
while(!S.empty())
S.pop();
while(n--)
{
cin >> op;
if(op == "push")
{
cin >> num;
S.push(num);
}
else if(op == "top")
{
if(S.empty())
cout << "empty" << endl;
else
cout << S.top() << endl;
}
else if(op == "pop")
{
if(S.empty())
cout << "error" << endl;
else
S.pop();
}
}
cout << endl;
}
return 0;
}