用栈实现一个队列

队列的介绍

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

队列的需要实现的接口

  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类型

posted on 2019-09-25 01:00  盛夏落木  阅读(451)  评论(0编辑  收藏  举报

导航