232.用栈实现队列 | 225. 用队列实现栈

86 阅读1分钟

用栈实现队列

题目描述:仅使用两个栈实现先入先出队列。支持一般队列支持的所有操作 push、pop、peek、empty

思路

将一个栈当作输入栈,用于 push 数据;另一个栈当作输出栈,用于 pop 和 peek

每次 pop 或 peek 时,若输出栈为空则将输入栈的全部数据依次弹出并压入输出栈,若输出栈不为空,则弹出输出栈的栈顶元素

这样输出栈从栈顶往栈底的顺序就是队列从队首往队尾的顺序。

代码

class MyQueue {
public:
    stack<int> s1;  // 输入栈
    stack<int> s2;  // 输出栈

    MyQueue() {

    }
    
    void push(int x) {
        s1.push(x);
    }
    
    int pop() {
        if (s2.empty() != 1) // 输出栈不为空
        {
            int x = s2.top();
            s2.pop();
            return x;
        }
        else // 输出栈为空:需要将输入栈移到输出栈
        {
            while (s1.empty() != 1)
            {
                int x = s1.top();
                s1.pop();
                s2.push(x);
            }
            int x = s2.top();
            s2.pop();  // 删除栈s1中栈底元素
            return x;
        }
    }
    
    int peek() {
        if (s2.empty() != 1) // 输出栈不为空
        {
            int x = s2.top();
            return x;
        }
        else
        {
            while (s1.empty() != 1)
            {
                int x = s1.top();
                s1.pop();
                s2.push(x);
            }
            return s2.top(); 
        }
    }
    
    bool empty() {
        if (s1.empty() == 1 && s2.empty() == 1)
            return true;
        return false;
    }
};

/**
 * 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();
 */

用队列实现栈

题目描述:

代码

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

    }
    
    void push(int x) {
        q.push(x);
    }
    
    int pop() {
        int n = q.size();
        for (int i = 0; i < n - 1; i++)
        {
            int x = q.front();
            q.pop();
            q.push(x);
        }
        int x = q.front();
        q.pop();
        return x;
    }
    
    int top() {
        int n = q.size();
        for (int i = 0; i < n - 1; i++)
        {
            int x = q.front();
            q.pop();
            q.push(x);
        }
        int x = q.front();
        q.pop();  // 一定要先pop,再push进去
        q.push(x);
        return x;
    }
    
    bool empty() {
        if (q.empty() == 1)
            return true;
        return false;
    }
};

/**
 * 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();
 */