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()获得栈顶元素,时间