环形队列的实现

vs2013下编写的项目工程见 我的 github: https://github.com/excelentone/DataStruct
CircleQueue.h

#include<iostream>
using namespace std;
template<class T>
class Queue
{
public:
    Queue(size_t size = 0) :_capacity(size),
        _head(0),
        _rear(0),
        _pBuf(new T[size]),
        _QueueLen(0)
    {}
    Queue(const Queue &q)
    {
        _pBuf = new T[q._capacity];
        for (size_t i = 0; i < q._capacity; i++)
        {
            _pBuf[i] = q._pBuf[i];
        }
        _capacity = q._capacity;
        _QueueLen = q._QueueLen;
        _rear = q._rear;
        _head = q._head;
    }
    Queue &operator=(const Queue &q)
    {
        if (this != &q)
        {
            delete[]_pBuf;
            _pBuf = new T[q._capacity];

            for (size_t i = 0; i < q._capacity; i++)
            {
                _pBuf[i] = q._pBuf[i];
            }
            _QueueLen = q._QueueLen;
            _capacity = q._capacity;
            _rear = q._rear;
            _head = q._head;
        }
        return *this;
    }
    bool QueueFull()
    {
        return _QueueLen == _capacity;
    }
    void Enqueue(const T data)
    {
        if (!QueueFull())
        {
            _pBuf[_rear] = data;
            _rear = (_rear + 1) % _capacity;
            _QueueLen++;
        }
        else
        {
            cout << "¶ÓÁÐÒÑÂú" << endl;
        }
    }
    bool QueueEmpty()
    {
        return _QueueLen == 0;
    }
    void Dequeue()
    {
        if (!QueueEmpty())
        {
            _head = (_head + 1) % _capacity;
            _QueueLen--;
        }
    }
    friend ostream& operator<<(ostream &os, const Queue &q)
    {
        for (size_t i = q._head; i < q._head + q._QueueLen; i++)
        {
            os << q._pBuf[i%q._capacity] << " ";
        }
        return os;
    }
    ~Queue()
    {
        if (NULL != _pBuf)
        {
            delete[]_pBuf;
        }
    }
private:
    T *_pBuf;
    size_t _capacity;
    size_t _QueueLen;
    size_t _head;
    size_t _rear;
};

test.cpp

#include"circleQueue.h"

void test()
{
    Queue<int> *p = new Queue<int>(4);

    p->Enqueue(5);
    p->Enqueue(6);
    p->Enqueue(7);
    p->Enqueue(8);
    p->Enqueue(9);
    cout << *p << endl;
    Queue<int> a(10);
    a.Enqueue(1);
    a.Enqueue(2);
    a.Enqueue(3);
    a.Enqueue(4);
    cout << a << endl;
    Queue<int> b(a);
    cout << b << endl;
    Queue<int> c(3);
    c = a;
    cout << c << endl;
}
int main()
{
    test();
    system("pause");
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值