OJ_2_两个栈实现一个队列以及两个队列实现一个栈

 

  1 #include <iostream>
  2 #include <stack>
  3 #include <queue>
  4 
  5 using namespace std;
  6 
  7 //用两个栈实现一个队列;
  8 /***
  9  *  思路:队列是先进先出;
 10  *      push操作:对stack1压栈
 11  *      pop操作:
 12  *          如果stack2不为空,对stack2栈顶元素出栈;
 13  *          如果stack2为空,对stack1出栈,出栈元素压入到stack2中。直到stack1为空。然后将stack2栈顶出栈;
 14  *
 15  */
 16 void queue_push(stack<int> &sk1,int num){
 17     sk1.push(num);
 18 }
 19 
 20 int queue_pop(stack<int> &sk1,stack<int> &sk2){
 21     int num;
 22     if(sk2.empty()){
 23         if(sk1.empty())
 24             return -1;
 25         while(!sk1.empty()){
 26             num = sk1.top();
 27             sk1.pop();
 28             sk2.push(num);
 29         }
 30         num = sk2.top();
 31         sk2.pop();
 32     }
 33     else{
 34         num = sk2.top();
 35         sk2.pop();
 36     }
 37     return num;
 38 }
 39 
 40 //用两个队列实现一个栈
 41 /***
 42  * 思路:栈是先进后出
 43  *      push操作:对queue1入队;
 44  *      pop操作:
 45  *          如果queue1为空,则将queue2中元素出队,依次压入queue1中,直到queue2剩下最后一个元素,将最后一个元素出队,即为出栈元素;
 46  *          如果queue1不为空,对queue1出队,出队元素压入queue2中。直到queue1剩下最后一个元素,将最后一个元素出队即为出栈的元素;
 47  */
 48 void stack_push(queue<int> & queue1,int num){
 49     queue1.push(num);
 50 }
 51 
 52 int stack_pop(queue<int> & queue1, queue<int> & queue2){
 53     int num;
 54     if(queue1.empty())
 55     {
 56         if(queue2.empty())
 57             return -1;
 58         while(queue2.size() != 1){
 59             num = queue2.front();
 60             queue2.pop();
 61             queue1.push(num);
 62         }
 63         num = queue2.front();
 64         queue2.pop();
 65     }
 66     else{
 67         while(queue1.size()!=1){
 68             num = queue1.front();
 69             queue1.pop();
 70             queue2.push(num);
 71         }
 72         num = queue1.front();
 73         queue1.pop();
 74     }
 75     return num;
 76 }
 77 
 78 int main()
 79 {
 80     int n1,n2,n3;
 81     queue<int> q1;
 82     queue<int> q2;
 83     stack<int> sk1;
 84     stack<int> sk2;
 85     while(cin>>n1>>n2>>n3){
 86         stack_push(q1,n1);
 87         stack_push(q1,n2);
 88         stack_push(q1,n3);
 89         cout<<"stack:"<<endl;
 90         cout<<stack_pop(q1,q2)<<endl;
 91         cout<<stack_pop(q1,q2)<<endl;
 92         cout<<stack_pop(q1,q2)<<endl;
 93 
 94 
 95         queue_push(sk1,n1);
 96         queue_push(sk1,n2);
 97         queue_push(sk1,n3);
 98         cout<<"queue"<<endl;
 99         cout<<queue_pop(sk1,sk2)<<endl;
100         cout<<queue_pop(sk1,sk2)<<endl;
101         cout<<queue_pop(sk1,sk2)<<endl;
102     }
103     return 0;
104 }

 

posted @ 2020-02-25 09:42  Grooovvve  阅读(185)  评论(0编辑  收藏  举报