zoukankan      html  css  js  c++  java
  • 剑指offer系列2:用两个栈实现队列

    第7题

     1 #include<iostream>
     2 #include<stack>
     3 #include<vector>
     4 using namespace std;
     5 class Solution
     6 {
     7 public:
     8     void push(int node) {
     9         stack1.push(node);
    10     }
    11 
    12     int pop() {
    13         int node = 0;
    14         if (stack1.empty() == true&& stack2.empty() == true)
    15         {
    16             //cout << "no node to pop!" << endl;
    17             return -1;
    18         }
    19         if (stack2.empty ()!= true)
    20         {
    21             node = stack2.top();
    22             stack2.pop();
    23             return node;
    24         }
    25         else
    26         {
    27             while (stack1.empty() != true)
    28             {
    29                 stack2.push(stack1.top());
    30                 stack1.pop();
    31             }
    32             node = stack2.top();
    33             stack2.pop();
    34             return node;    
    35         }
    36      }
    37     bool empty()
    38     //开始在这里报错 ,提示solution里没有empty函数。
    39     {
    40         return(stack1.empty ()== true && stack2.empty ()== true);
    41     }
    42 
    43 private:
    44     stack<int> stack1;
    45     stack<int> stack2;
    46 };
    47 int main()
    48 {
    49     Solution solu;
    50     solu.push(1);
    51     solu.push(2);
    52     solu.push(3);
    53     solu.push(4);
    54 
    55     int node;
    56     while (solu.empty() != true)
    57     {
    58 
    59         cout << solu.pop();
    60     }
    61 
    62     return 0;
    63 }

    主要考察栈和队列的结构特征。栈和队列都是特殊的线性表,栈先进后出,队列相反。

  • 相关阅读:
    eg_5
    浅谈Java中的Hashmap
    java中方法传入参数时:值传递还是址传递?
    重温概率学(一)期望、均值、标准差、方差
    博客搬家
    golang sync/atomic
    单机配置kafka和zookeeper
    异步消息队列组件
    2017总结
    看完轻松年薪30w+
  • 原文地址:https://www.cnblogs.com/neverland0718/p/10880304.html
Copyright © 2011-2022 走看看