剑指 Offer 09. 用两个栈实现队列(c++/python/go)

在这里插入图片描述

//栈:后进先出,队列,先进先出
class CQueue {
public:
    stack<int>stack1,stack2;//创建两个栈
    CQueue() {
        while(!stack1.empty()){//清空两个栈元素
            stack1.pop();
        }
        while(!stack2.empty()){
            stack2.pop();
        }
    }
    
    void appendTail(int value) {
       stack1.push(value);//stack1用来插入值
    }
    
    int deleteHead() {
        if(stack2.empty()){//第二个栈支持删除操作,第二栈为空才能开始删除
            while(!stack1.empty()){
                stack2.push(stack1.top());//把stack1中的元素从顶部开始放到stack2中
                stack1.pop();
            }
        }
        if(stack2.empty()){
            return -1;
        }else{
            int deleteitem = stack2.top();//删除stack2顶部的元素,也就是之前stack1底部的元素,实现队列的先进先出
            stack2.pop();
            return deleteitem;
        }
        

    }
};


/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue* obj = new CQueue();
 * obj->appendTail(value);
 * int param_2 = obj->deleteHead();
 */

python:

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []
    def push(self, node):
        # write code here
        self.stack1.append(node)
    def pop(self):
        # return xx
        if not self.stack2://第二栈为空时
            while self.stack1://把第一个栈的值挨个push到第二个栈
                self.stack2.append(self.stack1.pop())
        //第二栈不为空时,返回第二个栈的top元素
        if self.stack2:
            return self.stack2.pop()
        else:
            return -1
        
            

go:

type CQueue struct {
    inStack,outStack []int
}


func Constructor() CQueue {
    return CQueue{}
}


func (this *CQueue) AppendTail(value int)  {
    this.inStack = append(this.inStack,value)
}


func (this *CQueue) DeleteHead() int {
    if(len(this.outStack) == 0){//
        if(len(this.inStack) == 0){
            return -1
        }else{
            for len(this.inStack) > 0 {
                this.outStack = append(this.outStack, this.inStack[len(this.inStack)-1])
                this.inStack = this.inStack[:len(this.inStack)-1]
            }
        }
    }
    delVal := this.outStack[len(this.outStack)-1]
    this.outStack = this.outStack[:len(this.outStack)-1]
    return delVal
}






/**
 * Your CQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.AppendTail(value);
 * param_2 := obj.DeleteHead();
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值