• 题目1512:用两个栈实现队列


    1 秒

    内存限制:128 兆

    特殊判题:

    提交:722

    解决:263

    题目描述:

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

    输入:

    每个输入文件包含一个测试样例。
    对于每个测试样例,第一行输入一个n(1<=n<=100000),代表队列操作的个数。
    接下来的n行,每行输入一个队列操作:
    1. PUSH X 向队列中push一个整数x(x>=0)
    2. POP 从队列中pop一个数。

    输出:

    对应每个测试案例,打印所有pop操作中从队列pop中的数字。如果执行pop操作时,队列为空,则打印-1。

    样例输入:
    3
    PUSH 10
    POP
    POP
    样例输出:
    10
    -1
    有一个case超时, 真不知道什么原因:
    #include<iostream>
    #include<stack>
    #include<string.h>
    using namespace std;
    
    class myQueue
    {
        public:
            void en(int x);
            int  de();
            int  sizeq();
            bool emptyq();
    
        private:
            stack<int>v1;
            stack<int>v2;
    };
    
    int myQueue::sizeq()
    {
        return v1.size() + v2.size();
    }
    
    bool myQueue::emptyq()
    {
        if(sizeq()==0)
            return true;
        return false;
    }
    
    void myQueue::en(int x)
    {
        v1.push(x);
    }
    
    int myQueue::de()
    {
        if(sizeq()==0)
            return -1; //the queue is empty
        int front_val;
        if(v1.size()==1)
        {
            front_val = v1.top();
            v1.pop();
            return front_val;
        }
        while(v1.size()!=1)
        {
            front_val = v1.top();
            v2.push(front_val);
            v1.pop();
        }
        front_val = v1.top();
        v1.pop();
        int temp_val;
        while(!v2.empty())
        {
           temp_val = v2.top(); 
           v1.push(temp_val);
           v2.pop();
        }
        return front_val;
    }
    
    int main()
    {
        int n;
        int val;
        char str[5];
        myQueue qu;
        while(cin>>n)
        {
            while(n--)
            {
                cin>>str;
                if(!strcmp(str,"PUSH"))
                {
                    cin>>val;
                    qu.en(val);
                }
                if(!strcmp(str,"POP"))
                cout<<qu.de()<<endl;
            }
        }
        return 0;
    }
    


    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    BZOJ 2212/BZOJ 3702
    BZOJ 4761 Cow Navigation
    BZOJ 3209 花神的数论题
    BZOJ 4760 Hoof, Paper, Scissors
    BZOJ 3620 似乎在梦中见过的样子
    BZOJ 3940 Censoring
    BZOJ 3942 Censoring
    BZOJ 3571 画框
    BZOJ 1937 最小生成树
    BZOJ 1058 报表统计
  • 原文地址:https://www.cnblogs.com/vintion/p/4116966.html
Copyright © 2020-2023  润新知