CareerCup-3.5

简介:

Implement a MyQueue class which implements a queue using two stacks

开始想到的方法是入队的时候数据进入栈0,出队的时候数据移入栈1再pop。看了答案方法更好。只需要单向挪动。问题在于思维定势,想到队列,总觉得这些数据必须按照顺序在一个栈里。

#include <iostream>  
using namespace std;  
typedef int Data;  

struct Node  
{  
    Node(Data d):data(d){next = NULL;};  
    Data data;  
    Node* next;  
};  

class Stack  
{  
public:  
    Stack():topNode(NULL){};  
    void pop()  
    {  
        if(topNode != NULL)  
        {  
            Node* p = topNode;  
            topNode = topNode->next;  
            delete p;  
        } else {  
            throw "Empty Stack";  
        }  
    };  
    Data top()  
    {  
        if(topNode != NULL)  
        {  
            return topNode->data;  
        } else {  
            throw "Empty Stack";  
        }  
    };  
    void push(Data data)  
    {  
        Node* d = new Node(data);  
        d->next = topNode;  
        topNode = d;  
    };  
    bool isEmpty(){return topNode == NULL;};  
private:  
    Node* topNode;  
};  

class MyQueue  
{  
public:  
    void enqueue(Data data)  
    {  
        stack[0].push(data);  
    };  
    Data dequeue()  
    {  
        if(stack[1].isEmpty())  
        {  
            while(!stack[0].isEmpty())  
            {  
                stack[1].push(stack[0].top());  
                stack[0].pop();  
            }  
        }  
        if(stack[1].isEmpty())  
            throw "Empty Queue";  
        Data data = stack[1].top();  
        stack[1].pop();  
        return data;  
    };  
    bool isEmpty(){return stack[0].isEmpty() && stack[1].isEmpty();};  
private:  
    Stack stack[2];  
};  

int main()  
{  
    MyQueue queue;  
    for(int i=0; i<5; i++)  
    {  
        queue.enqueue(i*2);  
        queue.enqueue(i*2+1);  
        cout<<queue.dequeue()<<endl;  
        cout<<queue.dequeue()<<endl;  
    }  
    system("pause");  
}; 

目录
相关文章
|
存储 Ubuntu Linux
掌握Linux环境变量(从零开始配置用户环境变量的完整指南)
本文来源:https://www.vps5.cn/通俗讲解Linux环境变量的作用与配置方法,重点介绍PATH、HOME等常用变量,教你如何通过~/.bashrc文件永久设置用户环境变量,并避免常见错误,适合Linux新手快速上手。
Visual Studio 2017 选中一段英文改为大写或小写
Visual Studio 2017 选中一段英文改为大写或小写
310 0
|
2天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8076 2
|
11天前
|
域名解析 人工智能 Linux
|
19天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10239 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
5天前
|
人工智能 安全 网络安全
|
10天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1539 5