【剑指offer】两个栈实现一个队列 push pop

本是古典 何须时尚 2022-07-12 02:59 222阅读 0赞

题目

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型


  1. class Solution
  2. {
  3. public:
  4. //stack1 push
  5. void push(int node) {
  6. stack1.push(node);
  7. }
  8. //stack2 pop
  9. int pop() {
  10. if (stack2.empty()) //!!!仅在pop栈非空时才可以压入数据
  11. {
  12. while (!stack1.empty())
  13. {
  14. stack2.push(stack1.top());
  15. stack1.pop();
  16. }
  17. }
  18. int value = stack2.top();
  19. stack2.pop();
  20. return value;
  21. }
  22. private:
  23. stack<int> stack1;
  24. stack<int> stack2;
  25. };

发表评论

表情:
评论列表 (有 0 条评论,222人围观)

还没有评论,来说两句吧...

相关阅读