1.stack的定義
要使用stack,應先添加頭文件#include <stack>, 并在頭文件下面加上
"using namespace std"
//定義
stack< typename > name;
2. stack容器內元素的訪問
由于棧(stack)本書就是一種后進先出的數據結構,在STL的stack中只能
通過top()來訪問棧頂元素.
#include <stdio.h>
#include <stack>
using namespace std;
int main() {stack<int> st;for(int i = 1; i <= 5; i++) {st.push(i); //push(i)用以把i壓入棧,故此處依次入棧 1 2 3 4 5}printf("%d\n", st.top()); //top取棧頂元素return 0;
}
3. stack常用函數實例解析
(1) push()
//push(x)將x入棧,時間復雜度為O(1)
(2) top()
//top()獲得棧頂元素,時間