目 录CONTENT

文章目录

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

如风
2023-03-10 / 0 评论 / 0 点赞 / 23 阅读 / 438 字

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

232. 用栈实现队列

思路:一个栈用来存入,一个栈用来处理pop,pop的时候如果出栈的那个栈为空将入栈的栈的数据全部拿过来

type MyQueue struct {
    inSt   []int
    outSt   []int
}


func Constructor() MyQueue {
    return MyQueue{
        make([]int, 0),
        make([]int, 0),
    }
}


func (this *MyQueue) Push(x int)  {
    this.inSt = append(this.inSt, x)
}


func (this *MyQueue) Pop() int {
    if len(this.outSt) == 0 {
        for len(this.inSt) != 0 {
            top := this.inSt[len(this.inSt) - 1]
            this.inSt = this.inSt[:len(this.inSt) - 1]
            this.outSt = append(this.outSt, top)
        }
    }
    res := this.outSt[len(this.outSt) - 1]
    this.outSt = this.outSt[:len(this.outSt) - 1]
    return res
}


func (this *MyQueue) Peek() int {
    top := this.Pop()
    this.outSt = append(this.outSt, top)
    return top
}


func (this *MyQueue) Empty() bool {
    return len(this.inSt) == 0 && len(this.outSt) == 0
}


/**
 * Your MyQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(x);
 * param_2 := obj.Pop();
 * param_3 := obj.Peek();
 * param_4 := obj.Empty();
 */
class MyQueue {
public:
    stack<int>  stackIn;
    stack<int> stackOut;

    MyQueue() {

    }
    
    void push(int x) {
        stackIn.push(x);
    }
    
    int pop() {
        // 输出栈为空的时候,导入输入栈的全部数据
        if(stackOut.empty()) {
            while(!stackIn.empty()) {
                stackOut.push(stackIn.top());
                stackIn.pop();
            }
        }
        int top = stackOut.top();
        stackOut.pop();
        return top;
    }
    
    int peek() {
        int res = this->pop();
        stackOut.push(res);
        return res;
    }
    
    bool empty() {
        return stackIn.empty() && stackOut.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();
 */

225. 用队列实现栈

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

    }
    
    void push(int x) {
        que.push(x);
    }
    
    int pop() {
        // 将除了队尾元素之外的元素重新入队
        int size = que.size() - 1;
        while(size -- ) {
            que.push(que.front());
            que.pop();
        }
        int res = que.front();
        que.pop();
        return res;
    }
    
    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();
 */
0

评论区