232.implement-queue-using-stacks.go 1.3 KB

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