思路

这道题目是让我们用栈来模拟实现队列。 我们知道栈和队列都是一种受限的数据结构。 栈的特点是只能在一端进行所有操作,队列的特点是只能在一端入队,另一端出队。
在这里我们可以借助另外一个栈,也就是说用两个栈来实现队列的效果。这种做法的时间复杂度和空间复杂度都是O(n)。
由于栈只能操作一端,因此我们peek或者pop的时候也只去操作顶部元素,要达到目的 我们需要在push的时候将队头的元素放到栈顶即可。
因此我们只需要在push的时候,用一下辅助栈即可。 具体做法是先将栈清空并依次放到另一个辅助栈中,辅助栈中的元素再次放回栈中,最后将新的元素push进去即可
image.png

  1. /**
  2. * Initialize your data structure here.
  3. */
  4. var MyQueue = function() {
  5. this.stack = []
  6. this.helperStack = []
  7. };
  8. /**
  9. * Push element x to the back of queue.
  10. * @param {number} x
  11. * @return {void}
  12. */
  13. MyQueue.prototype.push = function(x) {
  14. this.stack.push(x)
  15. };
  16. /**
  17. * Removes the element from in front of queue and returns that element.
  18. * @return {number}
  19. */
  20. MyQueue.prototype.pop = function() {
  21. while(this.stack.length) {
  22. this.helperStack.push(this.stack.pop())
  23. }
  24. let item = this.helperStack.pop()
  25. while(this.helperStack.length) {
  26. this.stack.push(this.helperStack.pop())
  27. }
  28. return item
  29. };
  30. /**
  31. * Get the front element.
  32. * @return {number}
  33. */
  34. MyQueue.prototype.peek = function() {
  35. return this.stack[0]
  36. };
  37. /**
  38. * Returns whether the queue is empty.
  39. * @return {boolean}
  40. */
  41. MyQueue.prototype.empty = function() {
  42. if(this.stack.length) return false
  43. return true
  44. };
  45. /**
  46. * Your MyQueue object will be instantiated and called as such:
  47. * var obj = new MyQueue()
  48. * obj.push(x)
  49. * var param_2 = obj.pop()
  50. * var param_3 = obj.peek()
  51. * var param_4 = obj.empty()
  52. */