232. 用栈实现队列
题目链接
题解:用两个栈来实现队列,一个用于接收元素,一个用于pop元素。其中重点在于pop函数,要把sin里的元素放进sout才可以pop。
class MyQueue {
public:
stack<int> sin;
stack<int> sout;
MyQueue() {
}
void push(int x) {
sin.push(x);
}
int pop() {
if(sout.empty()){
while(!sin.empty()){
sout.push(sin.top());
sin.pop();
}
}
int res=sout.top();
sout.pop();
return res;
}
int peek() {
int p=this->pop();
sout.push(p);
return p;
}
bool empty() {
return sout.empty()&&sin.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();
*/
}

225. 用队列实现栈
题目链接
题解:一个队列用来pop元素,另一个用来备份。同时备份队列记得随时清空。优化后可以使用一个队列就完成栈的模拟。
//两个队列
class MyStack {
public:
queue<int> a;
queue<int> b;
MyStack() {
}
void push(int x) {
a.push(x);
}
int pop() {
int size=a.size();
for(int i=size;i>1;i--){
b.push(a.front());
a.pop();
}
int res=a.front();
a.pop();
a=b;
while(!b.empty()){
b.pop();
}
return res;
}
int top() {
return a.back();
}
bool empty() {
return a.empty()&&b.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
//一个队列
class MyStack {
public:
queue<int> a;
MyStack() {
}
void push(int x) {
a.push(x);
}
int pop() {
int size=a.size();
for(int i=size;i>1;i--){
a.push(a.front());
a.pop();
}
int res=a.front();
a.pop();
return res;
}
int top() {
return a.back();
}
bool empty() {
return a.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/

20. 有效的括号
题目链接
题解:每一轮遍历字符串中的元素,有以下几种情况,1. 是(,那么把)进栈;2. 是{,那么}进栈;3. 是【,那么】进栈。4. 是右括号,但是和栈顶不匹配那么false;5. 是有括号,匹配,那么pop;6. 此时栈空了,但是字符串没有遍历完,那么false;7. 字符串遍历完了,但是栈里还有元素,那么false。
class Solution {
public:
bool isValid(string s) {
if(s.size()%2!=0) return false;
stack<char> std;
for(int i=0;i<s.size();i++){
if(s[i]=='(') std.push(')');
else if(s[i]=='{') std.push('}');
else if(s[i]=='[') std.push(']');
else if(std.empty()||std.top()!=s[i]) return false;
else std.pop();
}
return std.empty();
}
};

好久没写题目了,复建一下

被折叠的 条评论
为什么被折叠?



