当前位置:   article > 正文

面试题 03.05. 化栈为队

化栈为队

实现一个MyQueue类,该类用两个栈来实现一个队列。

  1. class MyQueue {
  2. public:
  3. /** Initialize your data structure here. */
  4. stack<int> st1;
  5. stack<int> st2;
  6. MyQueue() {
  7. }
  8. /** Push element x to the back of queue. */
  9. void push(int x) {
  10. st1.push(x);
  11. }
  12. /** Removes the element from in front of queue and returns that element. */
  13. int pop() {
  14. if(st2.empty())
  15. {
  16. while(!st1.empty())
  17. {
  18. st2.push(st1.top());
  19. st1.pop();
  20. }
  21. }
  22. int a = st2.top();
  23. st2.pop();
  24. return a;
  25. }
  26. /** Get the front element. */
  27. int peek() {
  28. if(st2.empty())
  29. {
  30. while(!st1.empty())
  31. {
  32. st2.push(st1.top());
  33. st1.pop();
  34. }
  35. }
  36. return st2.top();
  37. }
  38. /** Returns whether the queue is empty. */
  39. bool empty() {
  40. if(st2.empty() && st1.empty())
  41. return true;
  42. return false;
  43. }
  44. };
  45. /**
  46. * Your MyQueue object will be instantiated and called as such:
  47. * MyQueue* obj = new MyQueue();
  48. * obj->push(x);
  49. * int param_2 = obj->pop();
  50. * int param_3 = obj->peek();
  51. * bool param_4 = obj->empty();
  52. */
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/391019
推荐阅读
相关标签
  

闽ICP备14008679号