题目

https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/

思路

  1. /**
  2. * 思路:
  3. * 维护两个stack:stack1和stack2
  4. * appendTail:直接向stack1中push
  5. * deleteHead:
  6. * a、如果stack2中有元素,直接pop
  7. * b、如果stack2中没有元素,把stack1中的pop出来,再push到stack2中,return stack2.pop()
  8. * c、stack2和stack1都是空的直接返回-1
  9. */

解题

  1. var CQueue = function() {
  2. this.stack1 = []
  3. this.stack2 = []
  4. };
  5. /**
  6. * @param {number} value
  7. * @return {void}
  8. */
  9. CQueue.prototype.appendTail = function(value) {
  10. this.stack1.push(value)
  11. };
  12. /**
  13. * @return {number}
  14. */
  15. CQueue.prototype.deleteHead = function() {
  16. if (this.stack2.length === 0) {
  17. if (this.stack1.length === 0) {
  18. return -1
  19. }
  20. while(this.stack1.length !== 0) {
  21. this.stack2.push(this.stack1.pop())
  22. }
  23. return this.stack2.pop()
  24. }
  25. return this.stack2.pop()
  26. };
  27. /**
  28. * Your CQueue object will be instantiated and called as such:
  29. * var obj = new CQueue()
  30. * obj.appendTail(value)
  31. * var param_2 = obj.deleteHead()
  32. */