前言
上一個提到了通過數組和鏈表來實現堆棧,這裏我們通過C++中的stl來實現堆棧。畢竟我們在實際應用的時候幾乎不會自己去封裝stack這樣的數據結構,都是使用已經提供好的。
代碼
#include<iostream>
#include<stack>
using namespace std;
int main() {
stack<int> s;
// 入棧
for(int i=0; i < 5; i++)
s.push(i);
// 獲取尺寸
cout << "the size of stack " << s.size() << endl;
// 注意這裏的pop只是刪除棧頂元素,並不會有返回值
s.pop();
cout << "the size of stack " << s.size() << endl;
// 返回棧頂元素
printf("%d\n", s.top());
//遍歷stack
while(!s.empty()) {
printf("%d ", s.top());
s.pop();
}
printf("\n");
return 0;
}