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

    队列的介绍

    队列是一个先进先出的数据结构,像生活中吃饭排队,就是一个队列的现象,大家排成一排,谁先排的队,谁就先吃饭。
    队列是从尾部添加元素,从首部删除元素,现实生活中的排队,是从最后面排,排在第一位的人,获得相应的服务后,才离开

    队列的需要实现的接口

    1. 获取队首元素
    2. 往队列中添加元素
    3. 删除队列的元素
    4. 队列是否为空
    #include<iostream>
    #include<stack>
    using namespace std;
    class MyQueue{
    public:
        int GetFront();
        int Push(int);
        void Pop();
        bool IsEmpty();
    
    private:
        stack<int> head;
        stack<int> tail;
    };
    int MyQueue::GetFront(){
        if( !head.empty())
         {
            return head.top();
         }
        
        if(tail.empty()){
            return -1;
        }
    
        while( !tail.empty() ){
           int temp = tail.top();
           tail.pop();
           head.push(temp);
        }
       return head.top();
    }
    
    int MyQueue::Push(int e){
        tail.push(e);
    }
    
    void MyQueue::Pop(){
        if( !head.empty())
         {
            head.pop();
         }
        
        if(tail.empty()){
            return;
        }
    
        while( !tail.empty() ){
           int temp = tail.top();
           tail.pop();
           head.push(temp);
        }
         head.pop();
    }
    
    bool MyQueue::IsEmpty(){
         return head.empty() && tail.empty();
    }
    
    int main(){
        MyQueue q;
        for(int i=0; i<10 ;i++){
            q.Push(i);
        }
    
        while( !q.IsEmpty() ){
        int temp =  q.GetFront();
        cout<<temp<<" ";
        q.Pop();
        
        }
        cout<<endl;
       return 0;
    }
    

    后续会把这些代码,做成通用类型,而不仅仅支持队列放的元素只是int类型

    作者: 盛夏落木

    出处: https://www.cnblogs.com/wanshuafe/

    关于作者:专注云存储,文件系统领域,请多多赐教!

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 可邮件(wanshuafe@163.com)咨询.

  • 相关阅读:
    bzoj 5092: [Lydsy1711月赛]分割序列
    bzoj1173: [Balkan2007]Point
    bzoj1536: [POI2005]Akc- Special Forces Manoeuvres
    bzoj2178: 圆的面积并
    bzoj1043 下落的圆盘
    bzoj2674 Attack
    bzoj1201: [HNOI2005]数三角形
    bzoj3135: [Baltic2013]pipesd
    bzoj1760 [Baltic2009]Triangulation
    bzoj3136
  • 原文地址:https://www.cnblogs.com/wanshuafe/p/11582097.html
Copyright © 2011-2022 走看看