文章目錄
- 有效的括號
- 用隊列實現棧
- 兩個隊列實現棧
- 一個隊列實現棧
- 用棧實現隊列
- 設計循環隊列
- 最小棧
- 棧的壓入&彈出序列
- 逆波蘭表達式
隊列:先進先出 棧:后進先出
有效的括號
https://leetcode.cn/problems/valid-parentheses/
class Solution {
public:bool isValid(string s) {stack<char> st;//遍歷字符串,碰到左括號:進棧 碰到右括號:出棧頂元素判斷是否和該右括號匹配for(auto& ch:s){if(ch == '(' || ch == '[' || ch == '{') {st.push(ch);}else {//如果棧為空,說明括號是不匹配的if(st.empty()) return false;//出棧頂元素和當前右括號匹配char top = st.top();st.pop();if( ch ==')' && top != '(' || ch == ']' && top != '[' ||ch == '}' && top != '{')return false; }}return st.empty(); //如果最后棧為空,說明括號是匹配的}
};
用隊列實現棧
https://leetcode-cn.com/problems/implement-stack-using-queues/
兩個隊列實現棧
class MyStack {
public:MyStack() {}void push(int x) {NonEmptyQueue.push(x);//往不為空的隊列插入數據}int pop() {//將不空隊列的數據放到空隊列當中,直到不空隊列只有一個元素while(NonEmptyQueue.size() > 1){EmptyQueue.push(NonEmptyQueue.front());NonEmptyQueue.pop();}int front = NonEmptyQueue.front();NonEmptyQueue.pop();NonEmptyQueue.swap(EmptyQueue);//交換兩個隊列,保證EmptyQueue為空隊列return front;}int top() {return NonEmptyQueue.back();}bool empty</