zoukankan      html  css  js  c++  java
  • 用两个栈实现队列

     题目描述:

    用两个栈来实现一个队列,完成队列的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中的栈顶,弹出即可。正好实现了队列的功能。

  • 相关阅读:
    hdoj:2033
    hdoj:2032
    hdoj:2031
    hdoj:2029
    hdoj:2028
    hdoj:2027
    hdoj:2024
    hdoj:2023
    hdoj:2022
    hdoj:题目分类
  • 原文地址:https://www.cnblogs.com/dormant/p/5312028.html
Copyright © 2011-2022 走看看