leetcode 用栈实现队列

type MyQueue struct {
     InputStack  []int //输入栈
    OutputStack []int //输出栈
}


/** Initialize your data structure here. */
func Constructor() MyQueue {
    queue := MyQueue{[]int{}, []int{}}
    return queue
}


/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int)  {
    //元素加入输入栈
    this.InputStack = append(this.InputStack, x)
}


/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
    //当输出栈不为空的,那就直接取出输出栈顶元素
    if len(this.OutputStack) != 0 {
        x := this.OutputStack[len(this.OutputStack)-1]
        this.OutputStack = this.OutputStack[:len(this.OutputStack)-1]
        return x
    }
    //如果输出栈为空,但是输入栈不为空,那就把输入栈的元素放进输出栈,并去除栈顶元素
    if len(this.InputStack) != 0 {
        for i := len(this.InputStack); i > 0; i-- {
            this.OutputStack = append(this.OutputStack, this.InputStack[i-1])
            this.InputStack = this.InputStack[:len(this.InputStack)-1]
        }
        x := this.OutputStack[len(this.OutputStack)-1]
        this.OutputStack = this.OutputStack[:len(this.OutputStack)-1]
        return x
    }
    return 0 //两个栈都是空的
}


/** Get the front element. */
func (this *MyQueue) Peek() int {
    //如果存在输出栈元素 那就直接输出栈顶元素
     if len(this.OutputStack) != 0 {
        return this.OutputStack[len(this.OutputStack)-1]
    }
    if len(this.InputStack) != 0 {
        for i := len(this.InputStack); i > 0; i-- {
            this.OutputStack = append(this.OutputStack, this.InputStack[i-1])
            this.InputStack = this.InputStack[:len(this.InputStack)-1]
        }
        return this.OutputStack[len(this.OutputStack)-1]
    }
    return 0
}


/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
      if len(this.InputStack)+len(this.OutputStack) == 0 {
        return true
    }
    return false
}


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

参考链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值