用两个栈实现队列

 题目描述:

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

 

算法实现:

 

 1 #include<iostream>
 2 #include<stack>
 3 #include<string>
 4 
 5 using namespace std;
 6 stack<int> stack1;
 7 stack<int> stack2;
 8 
 9 void Push(const int &node){                      //对stack1进行push操作
10     stack1.push(node);
11 }
12 
13 int Pop(){                                        //将stack2进行pop操作
14     if(stack2.size() <= 0){
15         while(stack1.size() > 0){
16             int &data = stack1.top();
17             stack1.pop();
18             stack2.push(data);
19         }
20     }
21     
22     if(stack2.size() == 0){
23         return -1;
24     }
25     
26     int head = stack2.top();
27     stack2.pop();
28     
29     return head;
30 }
31 
32 int main(){
33     long num;
34     string str;
35     cin >> num;
36     
37     while(num-- > 0){
38         cin>>str;
39         if(str == "PUSH"){
40             int x;
41             cin>>x;
42             Push(x);
43         }
44         else if(str == "POP"){
45             int ls = Pop();
46             if(ls < 0){
47                 cout<<"-1"<<endl;
48             }else{
49                 cout<<ls<<endl;
50             }
51         }
52     }
53     return 0;
54 }

 

思想:将两个栈(我们这里称做stack1, stack2)。stack1用作push操作,stack2用作pop操作。我们知道队列是先进先出,所以如果有数据进队列,将数据压入stack1中,如果需要输出数据,先将stack1中的数据弹出同时压入stack2中,此时先进入stack1中的数据会在stack2中的栈顶,弹出即可。正好实现了队列的功能。

 

posted @ 2016-03-23 17:23  Dormant  阅读(347)  评论(0编辑  收藏  举报