栈 是先进后出,队列是先进先出
栈在stl不被看成是容器,底层逻辑是deque list vector
对外提供pop、push、top的接口
| 1 2 3(top)
- 用栈实现队列,构建一个入栈和一个出栈
1.Push直接Push
2.pop的时候如果出栈是空的,就要入栈的元素输入到出栈,注意先读取栈顶元素,再弹出,如果先弹出就会少元素
3.peek读取栈顶元素,直接类调用pop函数,int res=this->pop(),栈顶元素被弹出,要把他放进去
class MyQueue {
public:
stack<int> stackin;
stack<int> stackout;
MyQueue() {
}
void push(int x) {
stackin.push(x);
}
int pop() {
if(stackout.empty()){
while(!stackin.empty()){
stackout.push(stackin.top());
stackin.pop();
}
}
int res=stackout.top();
stackout.pop();
return res;
}
int peek() {
int res=this->pop();//类的调用,只是取出数值,要把栈顶的值放进去
stackout.push(res);
return res;
}
bool empty() {
return stackin.empty()&&stackout.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
-
队列对外提供 push pop front,先进先出
-
出 1(front) 2 3(back) 入
-
Pop,出 1 2 3入,将front加入到队列后面,size-1次,变成 出3 2 1入
class MyStack {
public:
queue<int> que;
MyStack() {} void push(int x) { que.push(x); } // 1 2 3 // 3 2 1 int pop() { int size=que.size(); size--; while(size--){ que.push(que.front()); que.pop(); } int res=que.front(); que.pop(); return res; } int top() { int res=this->pop(); que.push(res); return res; } bool empty() { return que.empty(); }
};
-
有效的括号 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
-
匹配的问题考虑用栈
左括号的话,Push对应的右括号,如果和top相等就Pop
一共有三种情况
左括号多了( ( 【 】 ),剩余)
( 】,如果和top不相等
右括号多了 ( )】,还没有遍历完,栈就空了
class Solution {
public:
bool isValid(string s) {
if(s.size()%2==1) return false;
stack<int> st;
for(int i=0;i<s.size();i++){
if(s[i]=='(') st.push(')');
else if(s[i]=='[') st.push(']');
else if(s[i]=='{') st.push('}');
else if(st.empty()||st.top()!=s[i]) return false;//2 3
else st.pop();
}
return st.empty();//1
}
};
-
给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
示例:
-
输入:"abbaca"
-
输出:"ca"