简单的使用栈实现队列
private:
stack<int> instack; // 负责接收入队元素
stack<int> outstack; // 负责提供出队/查看队首元素
public:
MyQueue() {
}
void push(int x) {
instack.push(x);
}
int pop() {
if(outstack.empty()){
if(instack.empty()) return -1;
while(!instack.empty()){
outstack.push(instack.top()); // 先获取栈顶值
instack.pop(); // 再删除栈顶元素}
}
}
if (outstack.empty()) {
return -1;
}
int front = outstack.top();
outstack.pop();
return front;
}
int peek() {
if(!outstack.empty())
return outstack.top();
else{
if(instack.empty()) return -1;
while(!instack.empty()){
outstack.push(instack.top()); // 先获取栈顶值
instack.pop(); // 再删除栈顶元素
}
return outstack.top();
}
}
bool empty() {
if(outstack.empty()&&instack.empty()) return true;
else return false;
}
};
使用队列实现栈
private:
queue<int> intque;
public:
MyStack() {
}
void push(int x) {
intque.push(x);
}
int pop() {
// 空栈处理
if (intque.empty()) return -1;
int n = intque.size();
// 将前n-1个元素移到队列尾部,让原队尾(栈顶)到队首
for (int i = 0; i < n - 1; ++i) {
// 修正:先取队首值 → 移到队尾 → 删除原队首
int front_val = intque.front();
intque.push(front_val);
intque.pop();
}
// 此时队首就是栈顶元素,取出并删除
int top_val = intque.front();
intque.pop();
return top_val;
}
int top() {
if (intque.empty()) return -1;
int n = intque.size();
// 同样将前n-1个元素移到队尾
for (int i = 0; i < n - 1; ++i) {
int front_val = intque.front();
intque.push(front_val);
intque.pop();
}
// 取出栈顶值(此时队首)
int top_val = intque.front();
// 修正:将栈顶值重新放回队尾(避免丢失)
intque.push(top_val);
intque.pop();
return top_val; // 直接
}
bool empty() {
return intque.empty();
}
};
用栈来处理括号问题,实际可以延申学习参考逆波兰表达式的计算处理,另外需要注意的是,此处的cpp库中的stack.pop(),不返回值
public:
bool isValid(string s) {
// 栈存储“待匹配的右括号”(左括号入栈时,压入对应的右括号)
stack<char> bracketStack; // 重命名count为bracketStack,语义更清晰
int n = s.size();
// 边界条件:空字符串或长度为奇数,直接返回false(括号无法成对)
if (n % 2 != 0 || n == 0) {
return false;
}
for (int i = 0; i < n; ++i) {
// 核心修正:switch后跟表达式s[i],并补全大括号
switch (s[i]) {
case '(':
// 左圆括号 → 压入对应的右圆括号,等待匹配
bracketStack.push(')');
break;
case '{':
// 左大括号 → 压入对应的右大括号
bracketStack.push('}');
break;
case '[':
// 左方括号 → 压入对应的右方括号
bracketStack.push(']');
break;
// 处理右括号()、}、])
case ')':
case '}':
case ']':
// 关键修正1:先检查栈是否为空(避免top()崩溃)
if (bracketStack.empty()) {
return false;
}
// 关键修正2:判断栈顶是否等于当前右括号(匹配则弹出,不匹配则返回false)
if (bracketStack.top() == s[i]) {
bracketStack.pop();
} else {
return false; // 括号不匹配,直接返回false
}
break;
// 处理非括号字符(可选:如果输入只有括号,可省略)
default:
return false; // 包含非括号字符,视为不合法
}
}
// 关键:遍历结束后,栈必须为空(所有左括号都匹配完成)
return bracketStack.empty();
}
};
用栈来实现删除相邻重复元素
```class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
int n=s.size();
for(int i=0;i<n;i++){
if(st.empty()){
st.push(s[i]);
}
else{
if(st.top()==s[i])
st.pop();
else
st.push(s[i]);
}
}
string result;
while (!st.empty()) {
// 栈是后进先出,先拼接的是栈顶(逆序)
result += st.top();
st.pop();
}
// 反转字符串,恢复正确顺序
reverse(result.begin(), result.end());
return result; // 返回字符串,而非栈
}
};