C++队列的用法及队列的实现

继c++栈之后的队列使用

  1. 首先看一下原c++队列的方法的基本用法:
    1. back()返回最后一个元素
    2. empty()如果队列空则返回真
    3. front()返回第一个元素
    4. pop()删除第一个元素
    5. push()在末尾加入一个元素
    6. size()返回队列中元素的个数
  2. 代码示例:
#include<iostream>
#include<queue>
using namespace std;

int main()
{
    queue<int> que;
    //入队
    for(int i=0;i<50;i++)
    {
        que.push(i);
    }
    cout<<"队列的大小:"<<que.size()<<endl;
    while(!que.empty())
    {
        cout<<"队首元素:"<<que.front()<<"  ";
        cout<<"队尾元素:"<<que.back()<<endl;
        que.pop();
    }
    cout<<"队列的大小:"<<que.size()<<endl;
    return 0;
}
  1. 接下来我们自己写队列,这时仍然要用到c++中的模板类(template)
#include<iostream>
using namespace std;

//结点
template<class type>
class note
{
public:
    type data;
    note* next;
    note(type data):data(data),next(NULL){}
    ~note()
    {
        next=NULL;
    }
};

template<class type>
class my_queue
{
    //前后指针
    note<type>* _front;
    note<type>*_back;
    note<type>* _note;
    int size;
public:
    my_queue():size(-1)
    {
        _back=_front=NULL;
    }
    ~my_queue()
    {
        delete _front;
        delete _back;
        delete _note;
        _back=_front=_note=NULL;
    }
    void Push(type data);
    void Pop();
    bool Empty();
    type Front();
    type Back();
    int Size();
};

template<class type>
void my_queue<type>::Push(type data)
{
    _note=new note<type>(data);
    _note->next=NULL;
    if(_front==NULL)
    {
        _front=_back=_note;
    }
    else
    {
        _back->next=_note;
        _back=_note;
    }
    size++;
}

template<class type>
void my_queue<type>::Pop()
{
    if(!Empty())
    {
        _note=_front;
        _front=_front->next;
        delete _note;
        _note=NULL;
        size--;
    }
    else
    {
        cout<<"队列为空\n";
    }
}

template<class type>
bool my_queue<type>::Empty()
{
    if(size>-1){
        return false;
    }
    else
    {
        return true;
    }
}

template<class type>
type my_queue<type>::Front()
{
    if(!Empty())
    {
        return _front->data;
    }
    else
    {
        cout<<"队列为空\n";
    }
}

template<class type>
type my_queue<type>::Back()
{
    if(!Empty())
    {
        return _back->data;
    }
    else
    {
        cout<<"队列为空\n";
    }
}

template<class type>
int my_queue<type>::Size()
{
        return size+1;
}
  1. 然后就可以在另一个cpp文件中使用它了(记得include):
#include<iostream>
#include"my_queue.cpp"
using namespace std;

int main()
{
    my_queue<int> que;
    //入队
    for(int i=0;i<50;i++)
    {
        que.Push(i);
    }
    cout<<"队列的大小:"<<que.Size()<<endl;
    while(!que.Empty())
    {
        cout<<"队首元素:"<<que.Front()<<"  ";
        cout<<"队尾元素:"<<que.Back()<<endl;
        que.Pop();
    }
    cout<<"队列的大小:"<<que.Size()<<endl;
    cout<<"队列类的大小"<<sizeof(que);
    return 0;
}
  1. 最后sizeof的大小也是比我写的大,即c++提供的队列要比我复杂,或者说是完备

猜你喜欢

转载自blog.csdn.net/qq_20366761/article/details/70158762