队列实现栈以及栈实现队列
用栈实现队列
https://leetcode-cn.com/problems/implement-queue-using-stacks/
两个栈来回倒,其中一个的栈顶就是最后进入的,push 的时候压进这个栈;另一个栈的栈顶是最先进入的,pop 和 peek 的时候弹出这个栈顶。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
   | type MyQueue struct {     s1, s2 []int }
 
  func Constructor() MyQueue {     return MyQueue{make([]int, 0), make([]int, 0)} }
 
  func (this *MyQueue) Push(x int)  {          for len(this.s2) != 0 {         top := this.s2[len(this.s2)-1]         this.s2 = this.s2[:len(this.s2)-1]         this.s1 = append(this.s1, top)     }
           this.s1 = append(this.s1, x) }
 
  func (this *MyQueue) Pop() int {          for len(this.s1) != 0 {         top := this.s1[len(this.s1)-1]         this.s1 = this.s1[:len(this.s1)-1]         this.s2 = append(this.s2, top)     }
           top := this.s2[len(this.s2)-1]     this.s2 = this.s2[:len(this.s2)-1]     return top }
 
  func (this *MyQueue) Peek() int {          for len(this.s1) != 0 {         top := this.s1[len(this.s1)-1]         this.s1 = this.s1[:len(this.s1)-1]         this.s2 = append(this.s2, top)     }
           return this.s2[len(this.s2)-1] }
 
  func (this *MyQueue) Empty() bool {     return len(this.s1) + len(this.s2) == 0 }
 
  | 
 
用队列实现栈
https://leetcode-cn.com/problems/implement-stack-using-queues/
只用一个队列即可。栈顶元素就是队尾,入队时记下来。弹出栈顶元素时,将其他元素全部出队并重新入队,注意记住下一个栈顶元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
   | type MyStack struct {     top int     q []int }
 
  func Constructor() MyStack {     return MyStack{} }
 
  func (this *MyStack) Push(x int)  {     this.q = append(this.q, x)     this.top = x   }
 
  func (this *MyStack) Pop() int {     sz := len(this.q) - 2     for sz > 0 {                  front := this.q[0]         this.q = this.q[1:]         this.q = append(this.q, front)         sz--     }          nextTop := this.q[0]     this.q = this.q[1:]     this.q = append(this.q, nextTop)
      this.top = nextTop
           top := this.q[0]     this.q = this.q[1:]     return top }
 
  func (this *MyStack) Top() int {     return this.top }
 
  func (this *MyStack) Empty() bool {     return len(this.q) == 0 }
 
  |