力扣刷题队列和栈

打卡go学习第二天之力扣刷题队列和栈

力扣:232. 用栈实现队列


type MyQueue struct {
   Stack1 []int
   Stack2 []int
}

func Constructor() MyQueue {
   return MyQueue{
      Stack1: nil,
      Stack2: nil,
   }
}

// 规定stack1为队尾,stack2为队头
func (queue *MyQueue) Push(x int) {
   queue.Stack1 = append(queue.Stack1, x)
}

// 先对stack2的长度判空,是空的就把stack1弹到stack2中,这有stack2的长度就会大于0,然后把len(queue.Stack2)-1弹出
func (queue *MyQueue) Pop() int {
   if len(queue.Stack2) == 0 {
      for len(queue.Stack1) != 0 {
         queue.Stack2 = append(queue.Stack2, queue.Stack1[len(queue.Stack1)-1])
         queue.Stack1 = queue.Stack1[:len(queue.Stack1)-1]
      }
   }
   if len(queue.Stack2) > 0 {
      val := queue.Stack2[len(queue.Stack2)-1]
      queue.Stack2 = queue.Stack2[:len(queue.Stack2)-1]
      return val
   }
   return -1
}

func (queue *MyQueue) Peek() int {
   if len(queue.Stack2) != 0 {
      return queue.Stack2[len(queue.Stack2)-1]
   } else {
      for len(queue.Stack1) != 0 {
         queue.Stack2 = append(queue.Stack2, queue.Stack1[len(queue.Stack1)-1])
         queue.Stack1 = queue.Stack1[:len(queue.Stack1)-1]
      }
      return queue.Stack2[len(queue.Stack2)-1]
   }
}

func (queue *MyQueue) Empty() bool {
   return len(queue.Stack1) == 0 && len(queue.Stack2) == 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();
 */

力扣:225. 用队列实现栈

type MyStack struct {
    queue1 []int
    queue2 []int
}

func Constructor() MyStack {
    return MyStack{}
}

func (this *MyStack) Push(x int) {
    this.queue2 = append(this.queue2, x)
    for len(this.queue1) > 0 {
        this.queue2 = append(this.queue2, this.queue1[0])
        this.queue1 = this.queue1[1:]
    }
    this.queue1, this.queue2 = this.queue2, this.queue1
}

func (this *MyStack) Pop() int {
    if len(this.queue1) > 0 {
        val := this.queue1[0]
        this.queue1 = this.queue1[1:]
        return val
    }
    return -1
}

func (this *MyStack) Top() int {
    if len(this.queue1) > 0 {
        return this.queue1[0]
    }
    return -1
}

func (this *MyStack) Empty() bool {
    return len(this.queue1) == 0
}


/**
 * Your MyStack object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(x);
 * param_2 := obj.Pop();
 * param_3 := obj.Top();
 * param_4 := obj.Empty();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值