232. 用栈实现队列 - 力扣(LeetCode)
一道模拟题,做之前要想清楚队列和栈各自的特点,用两个栈来实现队列的先进先出的特点,栈先进入的元素后出,在弹出时,将栈A中的元素依次转移到栈B中,这样元素顺序恰好反转,再从栈B中弹出各元素,就解决问题了。
class MyQueue {
public:
stack<int>inStack;
stack<int>outStack;
MyQueue() {
}
void push(int x) {
inStack.push(x);
}
int pop() {
if(outStack.empty()){
while(!inStack.empty()){
outStack.push(inStack.top());//存进出栈
inStack.pop();//弹出入栈
}
}
int result=outStack.top();
outStack.pop();
return result;
}
int peek() {
int res=this->pop();
outStack.push(res);
return res;
}
bool empty() {
//当进入栈和输出栈都是空的时候,队列自然就是空的
return inStack.empty()&& outStack.empty();
}
};
225. 用队列实现栈 - 力扣(LeetCode)
怎么用队列先进先出的特性完成现金后出的顺序,是这道题的关键点。我们可以使用两个队列,在栈输出时,将先进队列的前n-1个元素逐个储存到一个新的队列中,并逐个弹出,然后返归老队列第一个元素,就实现了这种功能。
class MyStack {
public:
queue<int>q1;
queue<int>q2;
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
int size=q1.size();
size--;
while(size--){
q2.push(q1.front());
q1.pop();
}
int result=q1.front();
q1.pop();
q1=q2;//将q2的值赋给q1
while(!q2.empty()){
q2.pop();
}
return result;
}
int top() {
int size=q1.size();
size--;
while(size--){
q2.push(q1.front());
q1.pop();
}
int result=q1.front();
q2.push(q1.front());
q1.pop();
q1=q2;
while(!q2.empty()){
q2.pop();
}
return result;
}
bool empty() {
return q1.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. 有效的括号 - 力扣(LeetCode)
需要注意在判断第三种情况时候,要先判断栈是否为空,如果为空直接返回假 。
else if(my_st.empty() || my_st.top()!=s[i])//正确
else if(my_st.top()!=s[i] || my_st.empty())//错误
如果判断条件写反了,会报错当输入是 ){ 这种情况时,栈是空的,和判断条件发生冲突,这个细节需要注意。
class Solution {
public:
bool isValid(string s) {
stack<char>my_st;
if(s.size()%2!=0) return false;//剪枝
for(int i=0;i<s.size();i++){
if(s[i]=='('){
my_st.push(')');
}
else if(s[i]=='['){
my_st.push(']');
}
else if(s[i]=='{'){
my_st.push('}');
}
//else if (my_st.empty() || my_st.top() != s[i]) return false;
else if(my_st.empty()||my_st.top()!=s[i]){
return false;
}
else{
my_st.pop();
}
}
return my_st.empty();
}
};
1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)
这个也属于匹配题目,是栈的经典应用。
class Solution {
public:
string removeDuplicates(string s) {
stack<char>st;
for(char a:s){
if(st.empty()||a!=st.top()){
st.push(a);
}
else{
st.pop();
}
}
string result="";
while(!st.empty()){
result+=st.top();
st.pop();
}
reverse(result.begin(),result.end());
return result;
}
};
484

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



