Loading

【算法训练营day10】理论基础 LeetCode232. 用栈实现队列 LeetCode225. 用队列实现栈

理论基础

栈常用函数

#include <stack>
stack<int> s;
s.empty();       // 如果栈为空则返回true,否则返回false
s.size();        // 返回栈中元素的个数
s.top();         // 返回栈顶元素,但不删除该元素
s.pop();         // 弹出栈顶元素,但不返回该元素值
s.push();        // 将元素压入栈顶

队列常用函数

#include <queue>
queue<int> q;
q.empty();       // 如果队列为空则返回true,否则返回false       
q.size();        // 返回队列中元素的个数
q.front();       // 返回队首元素,但不删除该元素
q.back();        // 返回队尾元素,但不删除该元素 
q.pop();         // 弹出队首元素,但不返回该元素值
q.push();        // 将元素压入队尾

LeetCode232. 用栈实现队列

题目链接:232. 用栈实现队列

初次尝试

今天的两道题用来复习栈与队列的基础知识的,没有太多的思考量,直接看题解复习。

看完代码随想录后的想法

思路不难,用两个栈屁股对屁股即可实现一个队列的功能,需要注意的就是:

  1. 队列中的某个元素不会同时存在于在stIn和stOut中,只会存在于其中一个栈。
  2. 栈的pop()函数并不会返回弹出的元素值,所以需要保存弹出的元素值时,先用top()再用pop()即可。
class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;

    MyQueue() {
    }
    
    void push(int x) {
        stIn.push(x);
    }
    
    int pop() {
        if (stOut.empty()) {
            while (!stIn.empty()) {
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;
    }
    
    int peek() {
        int result = this -> pop();
        stOut.push(result);
        return result;
    }
    
    bool empty() {
        return stIn.empty() && stOut.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();
 */

LeetCode225. 用队列实现栈

题目链接:225. 用队列实现栈

初次尝试

直接看题解复习。

看完代码随想录后的想法

仅用一个队列就可以实现栈,实现栈pop的思路为:在栈需要pop的时候,把队列除队尾元素之前的所有元素都依次pop,然后重新push进队列,这个时候队首的元素即为栈需要pop的元素。

class MyStack {
public:
    queue<int> que;

    MyStack() {
    }
    
    void push(int x) {
        que.push(x);
    }
    
    int pop() {
        for (int i = 0; i < que.size() - 1; i++) {
            que.push(que.front());
            que.pop();
        }
        int result = que.front();
        que.pop();
        return result;
    }
    
    int top() {
        return que.back();
    }
    
    bool empty() {
        return que.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();
 */
posted @ 2022-10-21 14:01  BarcelonaTong  阅读(32)  评论(0)    收藏  举报