赞
踩
目录
1. stack是一种容器适配器,专门用在具有后进先出操作的上下文环境中,其删除只能从容器的一端进行元素的插入与提取操作。
2. stack是作为容器适配器被实现的,容器适配器即是对特定类封装作为其底层的容器,并提供一组特定的成员函数来访问其元素,将特定类作为其底层的,元素特定容器的尾部(即栈顶)被压入和弹出。
3. stack的底层容器可以是任何标准的容器类模板或一些其他特定的容器类,这些容器类应该支持以下操作:
4. 标准容器vector、deque、list均符合这些需求,默认情况下,如果没有为stack指定特定的底层容器,默认情况下使用deque。
函数说明 | 接口说明 |
stack() | 构造空的栈 |
empty() | 检测stack是否为空 |
size() | 返回stack中元素的个数 |
top() | 返回栈顶元素的引用 |
push() | 将元素val压入stack中 |
pop() | 将stack中尾部的元素弹出 |
相关题目:
- class MinStack
- {
- public:
- void push(int val)
- {
- st.push(val);
- if (Min.empty() || val <= Min.top())
- Min.push(val);
- }
-
- void pop()
- {
- if (Min.top() == st.top())
- Min.pop();
-
- st.pop();
- }
-
- int top()
- {
- return st.top();
- }
-
- int getMin()
- {
- return Min.top();
- }
-
- private:
- stack<int> st;
- stack<int> Min;
- };

- class Solution
- {
- public:
- bool IsPopOrder(vector<int>& pushV, vector<int>& popV)
- {
- if (pushV.size() != popV.size())
- return false;
-
- int in = 0;
- int out = 0;
- stack<int> st;
- while (out < popV.size())
- {
- while (st.empty() || st.top() != popV[out])
- {
- if (in < pushV.size())
- st.push(pushV[in++]);
- else
- return false;
- }
-
- st.pop();
- out++;
- }
-
- return true;
- }
- };

从栈的接口可以看出,栈实际是一种特殊的vector,因此使用vector完全可以模拟实现stack。
- #define _CRT_SECURE_NO_WARNINGS 1
-
- #include<vector>
- #include<deque>
- using namespace std;
-
- namespace fyd
- {
- template<class T, class Container = deque<T>>
-
- class stack
- {
- public:
- void push(const T& x)
- {
- _con.push_back(x);
- }
-
- void pop()
- {
- _con.pop_back();
- }
-
- const T& top()
- {
- return _con.back();
- }
-
- bool empty()
- {
- return _con.empty();
- }
-
- size_t size()
- {
- return _con.size();
- }
-
- private:
- Container _con;
- };
- }

感谢各位大佬支持!!!
互三啦!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。