数据结构:面向对象+链表实现循环队列

LoopQueue.h

#include<iostream>
#include <cassert>

using namespace std;


//template<class T>
//class SeqQueue;
//template<class T>
//
//ostream& operator<< (ostream& out, SeqQueue<T>& Q)//将友元函数声明在前可以避免其警告友元函数未声明
//{
//    cout << "front = " << Q.front << ", rear = " << Q.rear << endl;
//    if (!Q.IsEmpty())
//    {
//        int i = Q.front;
//        while (i != Q.rear)
//        {
//            cout << Q.elements[i] << "  ";
//            i = (++i) % maxSize;
//        }
//    }
//    return out;
//
//}


template <typename T>
class LoopQueue
{
private:
    int front, rear;
    T* data;
    int MAXSIZE;
public:
    LoopQueue(int size) {
        front = rear = 0;
        MAXSIZE = size;
        this->data = new T[MAXSIZE];
        assert(this->data != NULL);
    }
	~LoopQueue() { 
        delete[] data;
    }

    bool push(const T& x);//入队列
    bool pop(T& x);//出队列
    bool getFront(T& x);//找队头
    void show();
    //判空
    bool IsEmpty()const {
        return (this->rear == this->front) ? true : false; 
    }
    //判满
    bool IsFull()const { 
        return ((this->rear + 1) % this->MAXSIZE == this->front) ? true : false;
    }
    //求队长
    int getSize()const { 
        return(this->rear - this->front + this->MAXSIZE) % this->MAXSIZE;
    }
    //friend ostream& operator<<<>(ostream& out, SeqQueue<T>& Q);
};

//入队列
template<typename T>
bool LoopQueue<T>::push(const T& x) {
    if (!this->IsFull()) {
        this->data[this->rear] = x;
        this->rear = (this->rear + 1) % this->MAXSIZE;
        return true;
    }
    return false;
}

//出队列
template<typename T>
bool LoopQueue<T>::pop(T& x) {
    if (!this->IsEmpty()) {
        x = this->data[this->front];
        this->front = (this->front + 1) % this->MAXSIZE;
        return true;
    }
    return false;
}

//返回队头
template<typename T>
bool LoopQueue<T>::getFront(T& x) {
    if (!this->IsEmpty()) {
        x = this->data[this->front];
        return true;
    }
    return false;
}
template <typename T>
void LoopQueue<T>::show() {
    if (!this->IsEmpty()) {
        cout << "front = " << this->front << ", rear = " << this->rear << endl;
        int i = this->front;
        while (i != this->rear)
        {
            cout << this->data[i] << " ";
            i = (++i) % this->MAXSIZE;
        }
        cout << endl;
    }
}

testLoopQueue.cpp

#include "LoopQueue.h"
#include <iostream>

using namespace std;

int main() {
	LoopQueue<int> Q(7);
	for (int i = 7; i > 0; i--) {
		Q.push(i);
	}
	Q.show();
	int q = 0;
	for (int i = 3; i >= 0; --i)
		Q.pop(q);
	Q.show();
	cout << "Size = " << Q.getSize() << endl;
}

运行结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值