剑指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 }

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

posted @ 2019-05-17 11:14  妮妮熊  阅读(116)  评论(0编辑  收藏  举报