【算法刷题day10】Leetcode:232.用栈实现队列、 225. 用队列实现栈

232.用栈实现队列

文档链接:[代码随想录]
题目链接:232.用栈实现队列
状态:ok 栈的使用

题目:
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
说明:
你 只能 使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
注意:
一个栈入队列一个栈出队列
1.定义栈:stack stIn;
2.判空:stIn.empty();
3.入栈:stIn.push(x);
4.出栈:stIn.pop();
5.返回栈顶元素:stIn.top();

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 res = this->pop();
        stOut.push(res);
        return res;
    }
    
    bool empty() {
        return stIn.empty() && stOut.empty();
    }
};

225. 用队列实现栈

文档链接:[代码随想录]
题目链接:225. 用队列实现栈
状态:

题目:
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意:
你只能使用队列的标准操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
注意:
一个队列操作一个队列备份
1.定义一个队列:queue quIn;
2.获取队列长度:quIn.size();
3.获取对头元素:quIn.front();
4.获取队尾元素:quIn.back();
5.入队:quIn.push(x)
6.出队:quIn.pop();
7.判空:quIN.empty();

class MyStack {
public:
    queue<int> quIn;
    queue<int> quOut;
    MyStack() {

    }
    
    void push(int x) {
        quIn.push(x);
    }
    
    int pop() {
        int size = quIn.size();
        size--;
        while(size--){
            quOut.push(quIn.front());
            quIn.pop();
        }
        int res = quIn.front();
        quIn.pop();
        quIn = quOut;
        while(!quOut.empty()){
            quOut.pop();
        }
        return res;
    }
    
    int top() {
        return quIn.back();
    }
    
    bool empty() {
        return quIn.empty();
    }
};

最近更新

  1. TCP协议是安全的吗?

    2024-04-01 20:06:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-01 20:06:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-01 20:06:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-01 20:06:01       20 阅读

热门阅读

  1. 深入探秘Python生成器:揭开神秘的面纱

    2024-04-01 20:06:01       15 阅读
  2. 计算机网络目录

    2024-04-01 20:06:01       17 阅读
  3. ChatGPT助力学术论文写作:方法与实践

    2024-04-01 20:06:01       20 阅读
  4. PostgreSQL中json_to_record函数的神秘面纱

    2024-04-01 20:06:01       18 阅读
  5. 如何利用ChatGPT提升学术研究的效率

    2024-04-01 20:06:01       16 阅读