232. 用栈实现队列(c++/go)

本文探讨了C++中使用栈实现的MyQueue类,通过stack进行数据的进出,并与Go语言的实现方式进行比较。重点介绍了类的方法如push、pop、peek和empty。同时,展示了如何实例化并操作这个队列结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

c++:

class MyQueue {
public:
    stack<int>stkin;
    stack<int>stkout;
    MyQueue() {

    }
    
    void push(int x) {
        stkin.push(x);

    }
    
    int pop() {
        if(stkout.empty()){// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
            while(!stkin.empty()){
                stkout.push(stkin.top());
                stkin.pop();
            }
        }
        int res = stkout.top();// stOut不为空的时候,取栈顶元素
        stkout.pop();
        return res;
    }
    
    int peek() {
        int res = this->pop();// 直接使用已有的pop函数
        stkout.push(res);// 因为pop函数弹出了元素res,所以再添加回去
        return res;
    }
    
    bool empty() {
        return stkout.empty() && stkin.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();
 */

go:

type MyQueue struct {
    stack []int
    back []int
}


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

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


func (this *MyQueue) Pop() int {
    if(len(this.back) == 0){
        for len(this.stack)!=0{
            val := this.stack[len(this.stack)-1]//取出stack的最后一个元素
            this.stack = this.stack[:len(this.stack)-1]//stack尾部去掉一个元素
            this.back = append(this.back,val)
        }
    }
    val := this.back[len(this.back)-1]
    this.back = this.back[:len(this.back)-1]
    return val
}


func (this *MyQueue) Peek() int {
    val := this.Pop()
    if val == 0{
        return 0
    }
    this.back = append(this.back,val)
    return val
}


func (this *MyQueue) Empty() bool {
    return len(this.back) == 0 && len(this.stack)==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();
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值