栈和队列part01

今天学习了栈和队列的第一部分。

  1. 基础知识
  2. 用栈模拟队列(双栈)
  3. 用队列模拟栈(一个队列,但是需要重复将队头元素写到队尾)
  4. 栈的基本应用(括号匹配、删除重复项、逆波兰表达式)

1. 基础知识

  1. 栈和队列是以底层容器完成其所有的工作,对外提供统一的接口,底层容器是可插拔的(也就是我们可以控制使用哪种容器来实现栈的功能)。
  2. 栈队列的底层实现可以是vector,deque,list , 主要就是数组和链表的底层实现。
  3. 所以STL 栈和队列也不被归类为容器,而被归类为container adapter( 容器适配器)。
  4. SGI STL中 栈和队列底层实现缺省情况下使用deque实现。deque是一个双向队列,只要封住一段,只开通另一端就可以实现栈的逻辑了。

2. 用栈实现队列(双栈)

题目:请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(pushpoppeekempty):

实现 MyQueue 类:

  • void push(int x) 将元素 x 推到队列的末尾
  • int pop() 从队列的开头移除并返回元素
  • int peek() 返回队列开头的元素
  • boolean empty() 如果队列为空,返回 true ;否则,返回 false

队列是两头进出,所以一个栈做不到,至少需要两个栈。一个输入栈,一个输出栈,这里要注意输入栈和输出栈的关系。

232.用栈实现队列版本2
  1. push:只要数据放进输入栈就好
  2. pop:输出栈如果为空,就把进栈数据全部导入进来,再从出栈弹出数据;如果输出栈不为空,则直接从出栈弹出数据就可以了
  3. peek:复用pop int res = this->pop();
class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;
    /** Initialize your data structure here. */
    MyQueue() {

    }
    /** Push element x to the back of queue. */
    void push(int x) {
        stIn.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        // 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
        if (stOut.empty()) {
            // 从stIn导入数据直到stIn为空
            while(!stIn.empty()) {
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;
    }

    /** Get the front element. */
    int peek() {
        int res = this->pop(); // 直接使用已有的pop函数
        stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
        return res;
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return stIn.empty() && stOut.empty();
    }
};
  • 时间复杂度: push和empty为O(1), pop和peek为O(n)
  • 空间复杂度: O(n)

3. 用队列模拟栈

题目:使用队列实现栈的下列操作:

  • push(x) -- 元素 x 入栈
  • pop() -- 移除栈顶元素
  • top() -- 获取栈顶元素
  • empty() -- 返回栈是否为空

a. 两个队列来实现栈

队列是先进先出的规则,把一个队列中的数据导入另一个队列中,数据的顺序并没有变,并没有变成先进后出的顺序,因此和上一题一样的思路不可行。

但是依然还是要用两个队列来模拟栈,只不过没有输入和输出的关系,而是另一个队列完全用来备份。如动画所示,把que1最后面的元素以外的元素都备份到que2,然后弹出最后面的元素,再把其他元素从que2导回que1

225.用队列实现栈

b. 使用一个队列实现栈

一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。

class MyStack {
public:
    queue<int> que;

    /** Initialize your data structure here. */
    MyStack() {
    }

    /** Push element x onto stack. */
    void push(int x) {
        que.push(x);
    }

    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int size = que.size();
        size--;
        while (size--) { // 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
            que.push(que.front());
            que.pop();
        }
        int result = que.front(); // 此时弹出的元素顺序就是栈的顺序了
        que.pop();
        return result;
    }

    /** Get the top element.
     ** Can not use back() direactly.
     */
    int top(){
        int size = que.size();
        size--;
        while (size--){
            // 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
            que.push(que.front());
            que.pop();
        }
        int result = que.front(); // 此时获得的元素就是栈顶的元素了
        que.push(que.front());    // 将获取完的元素也重新添加到队列尾部,保证数据结构没有变化
        que.pop();
        return result;
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return que.empty();
    }
};

4. 20有效的括号(栈)

题目:三种括号匹配。


  1. 碰到左括号,压入右括号!更好处理

  2. !mystack.empty()&& mystack.top() == s[i]注意,取top之前一定看看是否是空!!

bool isValid(string s) {
    int length = s.size();
    stack<char> mystack;
    for (int i = 0; i < length; i++) {
        if (s[i] == '(') mystack.push(')');
        else if (s[i] == '[') mystack.push(']');
        else if (s[i] == '{') mystack.push('}');
        else if (s[i] == ')'||s[i] == ']'||s[i] == '}') {//右括号
            if (!mystack.empty()&& mystack.top() == s[i]) {
                mystack.pop();
            } else
                return false; // 错误一:mystack是空,则右括号多;错误二:不匹配
        } else
            return false; //防止什么奇怪的错误
    }
    if (mystack.size() == 0) //string s中处理完后,栈中是空的才是完美结束
        return true;
    else //错误三:栈中不空,说明左括号多
        return false;
};

5. 1047. 删除字符串中的所有相邻重复项(栈)

题目:给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。在 S 上反复执行重复项删除操作,直到无法继续删除。在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

  • 输入:"abbaca"
  • 输出:"ca"

匹配问题常常使用栈。明显和上一题括号,都是栈的典型应用。

string removeDuplicates(string S) {
    stack<char> st;
    for (char s : S) {
        if (st.empty() || s != st.top()) {
            st.push(s);
        } else {
            st.pop(); // s 与 st.top()相等的情况
        }
    }
    string result = "";
    while (!st.empty()) { // 将栈中元素放到result字符串汇总
        result = st.top() + result;
        st.pop();
    }
    return result;
}

若是拿字符串直接作为栈,省去了栈还要转为字符串的操作:

string removeDuplicates(string S) {
    string result;
    for(char s : S) {
        if(result.empty() || result.back() != s) {
            result.push_back(s);
        }
        else {
            result.pop_back();
        }
    }
    return result;
}
  1. 可以使用栈来辅助做题,也可以直接将字符串作为栈。因为字符串有pop_back、push_back、back等操作。
  2. 字符串判空可以使用st.empty(),而不是size。

6. 150逆波兰表达式求值(栈)

题目:给你一个字符串数组 tokens ,表示一个根据 逆波兰表示法 表示的算术表达式。请你计算该表达式。返回一个表示表达式值的整数。

输入:tokens = ["2","1","+","3","*"]
输出:9
解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9


明显的栈的应用题。本题中每一个子表达式要得出一个结果,然后拿这个结果再进行运算,和上一题中删除字符串中的所有相邻重复项类似。遇到操作符就弹出两个进行运算。

  1. 使用long long

  2. string变为int或者long long:stoi、stoll

    char*变为int或者long long:atoi

    string变为char*:c_str()

    数字常量**(int,double,long等)转换为字符串(string):to_string

int evalRPN(vector<string>& tokens) {
    stack<long long> st; 
    for (int i = 0; i < tokens.size(); i++) {
        if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
            long long num1 = st.top();
            st.pop();
            long long num2 = st.top();
            st.pop();
            if (tokens[i] == "+") st.push(num2 + num1);
            if (tokens[i] == "-") st.push(num2 - num1);
            if (tokens[i] == "*") st.push(num2 * num1);
            if (tokens[i] == "/") st.push(num2 / num1);
        } else {
            st.push(stoll(tokens[i]));
        }
    }

    int result = st.top();
    st.pop(); // 把栈里最后一个元素弹出(其实不弹出也没事)
    return result;
}

今日古诗

柳梢青·送卢梅坡
刘过〔宋代〕

泛菊杯深,吹梅角远,同在京城。聚散匆匆,云边孤雁,水上浮萍。
教人怎不伤情。觉几度、魂飞梦惊。后夜相思,尘随马去,月逐舟行。

posted @ 2024-08-11 21:08  YueHuai  阅读(792)  评论(0)    收藏  举报