225.implement-stack-using-queues.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. type MyStack struct {
  2. Peek Queue
  3. Body Queue
  4. }
  5. /** Initialize your data structure here. */
  6. func Constructor() MyStack {
  7. return MyStack{make([]int, 0), make([]int, 0)}
  8. }
  9. /** Push element x onto stack. */
  10. func (this *MyStack) Push(x int) {
  11. this.Peek.Enqueue(x)
  12. if this.Peek.Size() == 2 {
  13. this.Body.Enqueue(this.Peek.Dequeue())
  14. }
  15. }
  16. /** Removes the element on top of the stack and returns that element. */
  17. func (this *MyStack) Pop() int {
  18. n := this.Body.Size()
  19. top := this.Peek.Dequeue()
  20. for i := 0; i < n-1; i++ {
  21. this.Peek.Enqueue(this.Body.Dequeue())
  22. }
  23. this.Peek, this.Body = this.Body, this.Peek
  24. return top
  25. }
  26. /** Get the top element. */
  27. func (this *MyStack) Top() int {
  28. return this.Peek.Front()
  29. }
  30. /** Returns whether the stack is empty. */
  31. func (this *MyStack) Empty() bool {
  32. return this.Peek.Empty()
  33. }
  34. /**
  35. * Your MyStack object will be instantiated and called as such:
  36. * obj := Constructor();
  37. * obj.Push(x);
  38. * param_2 := obj.Pop();
  39. * param_3 := obj.Top();
  40. * param_4 := obj.Empty();
  41. */
  42. // Queue ...
  43. type Queue []int
  44. // Dequeue ...
  45. func (q *Queue) Dequeue() int {
  46. front := (*q)[0]
  47. *q = (*q)[1:]
  48. return front
  49. }
  50. // Enqueue ...
  51. func (q *Queue) Enqueue(x int) {
  52. *q = append(*q, x)
  53. }
  54. // Front ...
  55. func (q Queue) Front() int {
  56. return q[0]
  57. }
  58. // Size ...
  59. func (q Queue) Size() int {
  60. return len(q)
  61. }
  62. // Empty ...
  63. func (q Queue) Empty() bool {
  64. return len(q) == 0
  65. }