力扣刷题队列和栈

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

你可能感兴趣的:(go打卡学习集合,1024程序员节)