[数据结构]队列的实现-C++

基于数组的循环队列的实现:


CycleQueueBaseArray.h:

#pragma once


template <class T>
class CycleQueueBaseArray {
private:
	T *array;
	int maxLength;
	int head;
	int tail;
public:
	CycleQueueBaseArray();
	CycleQueueBaseArray(int length);
	bool offer(T value);
	T poll();
	T peek();
	bool isEmpty();
	bool isFull();
};

CycleQueueBaseArray.cpp:

#include"CycleQueueBaseArray.h"

template <class T> CycleQueueBaseArray<T>::CycleQueueBaseArray() {
	array = new T[64];
	maxLength = 64;
	head = 0;
	tail = 0;
}

template <class T> CycleQueueBaseArray<T>::CycleQueueBaseArray(int length) {
	array = new T[length];
	maxLength = length;
	head = 0;
	tail = 0;
}

template <class T> bool CycleQueueBaseArray<T>::offer(T value) {
	if (!isFull()) {
		array[tail] = value;
		tail = (tail + 1) % maxLength;
		return true;
	}
	else {
		return false;
	}
}

template <class T> T CycleQueueBaseArray<T>::poll() {
	if (!isEmpty()) {
		head = (head + 1) % maxLength;
		return array[(head-1)%maxLength];
	}
	else {
		return NULL;
	}
}

template <class T> T CycleQueueBaseArray<T>::peek() {
	if (!isEmpty()) {
		return array[head];
	}
	else {
		return NULL;
	}
}

template <class T> bool CycleQueueBaseArray<T>::isEmpty() {
	if (head == tail) {
		return true;
	}
	else {
		return false;
	}
}

template <class T> bool CycleQueueBaseArray<T>::isFull() {
	if (head == (tail + 1) % maxLength) {
		return true;
	}
	else {
		return false;
	}
}



基于循环双指针链表的循环队列实现:

(循环双指针链表的实现在链表的实现



CycleQueueBaseCycleLinkedList.h:

#pragma once
#include"CycleLinkedList.h"

template <class T>
class CycleQueueBaseCycleLinkedList {
private:
	CycleLinkedList<T> list;
public:
	CycleQueueBaseCycleLinkedList();
	bool offer(T value);
	T poll();
	T peek();
	bool isEmpty();
};

CycleQueueBaseCycleLinkedList.cpp:

#include"CycleQueueBaseCycleLinkedList.h"

template <class T> CycleQueueBaseCycleLinkedList<T>::CycleQueueBaseCycleLinkedList() {

}

template <class T> bool CycleQueueBaseCycleLinkedList<T>::offer(T value) {
	return list.addAtTail(value);
}

template <class T> T CycleQueueBaseCycleLinkedList<T>::poll() {
	if (isEmpty()) {
		return NULL;
	}
	T value = list.getHead();
	list.deleteHead();
	return value;
}

template <class T> T CycleQueueBaseCycleLinkedList<T>::peek() {
	if (isEmpty()) {
		return NULL;
	}
	else {
		return list.getHead();
	}
}

template <class T> bool CycleQueueBaseCycleLinkedList<T>::isEmpty() {
	return list.isEmpty();
}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值