前言
作爲比較簡單的數據結構,使用C++容器庫中的棧(std::stack)也相對比較簡單。
在頭文件中,棧的定義爲:
template<
class T,
class Container = std::deque<T>
> class stack;
Stack
常用函數:
- top():訪問棧頂
- empty():判斷棧空
- size():返回棧中元素數
- push():向棧頂插入元素
- pop():刪除棧頂元素
代碼
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <stack>
using namespace std;
int main()
{
int n;
while (cin>>n) {
stack<int> s;
string ch;
int val;
while (n--) {
cin>>ch;
if (ch == "PUSH") {
cin>>val;
s.push(val);
} else if (ch == "POP") {
if (!s.empty())
s.pop();
} else if (ch == "TOP") {
if (!s.empty())
cout<<"Top : "<<s.top()<<endl;
else
cout<<"Empty"<<endl;
}
cout<<"Size : "<<s.size()<<endl;
}
cout<<endl;
}
}