算法训练营day9(补),栈与队列1

232. 用栈实现队列

package main

//思路用两个队列实现,利用栈先入后出着一特性,先让入第一个栈,然后讲第一个栈弹出同时入第二栈,此时就按队列实现先入先出了

type MyQueue struct {

//用数组模拟队列

  QueueIn  []int

  QueueOut []int

}

func Constructor() MyQueue {

  return MyQueue{QueueIn: []int{}, QueueOut: []int{}}

}

func (this *MyQueue) Push(x int) {

  this.QueueIn = append(this.QueueIn, x)

}

func (this *MyQueue) Pop() int {

  sizeIn := len(this.QueueIn)

  sizeOut := len(this.QueueOut)

  if sizeOut == 0 {

    if sizeIn == 0 {

      return -1

    }

     //把第一个栈弹出压入第二个栈

    for i := sizeIn - 1; i >= 0; i-- {

      this.QueueOut = append(this.QueueOut, this.QueueIn[i])

    }

         //把第一个栈清空

    this.QueueIn = []int{}

    sizeOut = len(this.QueueOut)

  }

  //每次弹出取最后一个值

  value := this.QueueOut[sizeOut-1]

//将栈缩减

  this.QueueOut = this.QueueOut[0 : sizeOut-1]

  return value

}

func (this *MyQueue) Peek() int {

  value := this.Pop()

  if value == -1 {

    return -1

  }

//因为不是真正弹出,拿到值后再放回

  this.QueueOut = append(this.QueueOut, value)

  return value

}

func (this *MyQueue) Empty() bool {

  return len(this.QueueIn) == 0 && len(this.QueueOut) == 0

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值