数据结构之队列

队列是一种特殊的线性表,它特殊之处在于它只能在头端进行删除操作,在后端进行插入操作。和栈具有相同的性质它也是一种操作受限制的线性表,通常又称为先进先出。它也是算法中常使用的重要知识。 接下来我的代码实现使用了c++中的模板类实现,这样操作比较灵活可以根据实际需要插入的类型进行操作,首先先介绍一下模板类的使用方法。

 

 

 

模板类:template<class T(形参名)>class< T > 类名 

#include<iostream>
using namespace std;
template<class T>class Fell {
public:
    T printf();
};
template<class T> T Fell<T>::printf()
{
    cout << "模板。" << endl;
    //return 0;
}
int main()
{
    Fell<void> a;
    a.printf();
    system("pause");
    return 0;
}

接下来我就给大家讲一下使用模板如何实现队列。其实实现的方法一样只是将代码灵活化,首先先插入data->pushData()函数,在插入数据的时候要考虑该队列是否已满判断函数->ifFull(),分两种情况1:满->用T *data=new T[maxRoom]开辟空间(加一)2:不满则data[front+1]=value;删除一样分两种情况1:空(不输出)2:非空->delete()函数实现,最后是输出则按照先进先出的原则即可。

 

具体代码实现如下:

/*队列*/
#include<iostream>
#define maxSize 10
using namespace std;
template<class T>class Queue {
private:
    T front;//插(前)
    T rear;//出(后)
    T data[maxSize];
    T maxRoom;
public:
    Queue();
    ~Queue();
    T pushData(T value);//插入data
    T ifFull();//判断是否满了
    T dalation();//扩容
    T deleteData();//删除data
    T ifEmpty();//判断是否为空
    T printf();//打印
};
template<class T>Queue<T>::Queue()
{
    front = -1;
    rear = 0;
    maxRoom = maxSize;
}
template<class T>Queue<T>::~Queue() { delete[]data; }
template<class T>T Queue<T>::pushData(T value)
{
    if (ifFull())
    {
        //扩容
        dalation();
        front = front + 1;
        data[front] = value;
    }
    else if (!ifFull())
    {
        front = front + 1;
        data[front] = value;
    }
    return 0;
}
template<class T>T Queue<T>::ifFull()
{
    if (front == maxRoom - 1)
    {
        return true;
    }
    else
        return false;
}
template<class T>T Queue<T>::dalation()
{
    maxRoom = maxRoom + 1;
    T *data = new T[maxRoom];
    return 0;
}
template<class T>T Queue<T>::deleteData()
{
    if (ifEmpty())
    {
        cout << "该队列为空队列." << endl;
    }
    else if (!ifEmpty())
    {
        rear = rear + 1;
    }
    return 0;
}
template<class T>T Queue<T>::ifEmpty()
{
    if (front == -1)
        return true;
    else
        return false;
}
template<class T>T Queue<T>::printf()
{
    if (rear > front)
    {
        cout << "该队列为空." << endl;
    }
    else
    {
        for (int i = rear; i <= front; i++)
        {
            cout << data[i] << endl;
        }
    }
  return 0;

}

int main()
{
    Queue<int> a;
    a.pushData(1);
    a.pushData(2);
    a.pushData(3);
    Queue<char> b;
    b.pushData('a');
    b.printf();
    //a.deleteData();
    a.printf();
    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值