#include <iostream>
#include <cassert>
using namespace std;
#define MAX_SIZE 8
template<class T>
class Queue
{
public:
Queue(); //初始化
T _array[MAX_SIZE];
int _front;
int _back;
};
template<class T>
Queue<T>::Queue()
{
_front = 0;
_back = 0;
}
template<class T>
void QueuePush(Queue<T>* q,T data)
{
assert(q);
if(q->_back == MAX_SIZE)
{
printf("队列的元素已满!!!\n");
return;
}
q->_array[q->_back++] = data;
}
template<class T>
void QueuePop(Queue<T>* q)
{
assert(q);
if(q->_front == MAX_SIZE)
{
printf("队列为空,无元素可出!!!\n");
}
q->_front++;
}
template<class T>
int QueueSize(Queue<T>* q)
{
assert(q);
return q->_back - q->_front;
}
//队首元素
template<class T>
T QueueTop(Queue<T>* q)
{
assert(q);
if(q->_front != MAX_SIZE)
return q->_array[q->_front];
else
{
printf("队列无元素!!!\n");
assert(1);
return -1;
}
}
//队尾元素
template<class T>
T QueueBack(Queue<T>* q)
{
assert(q);
if(q->_front != MAX_SIZE)
return q->_array[q->_back-1];
else
{
printf("队列无元素!!!\n");
assert(1);
return -1;
}
}
//判断队列是否为空
template<class T>
int QueueEmpty(Queue<T>* q)
{
assert(q);
if(q->_front == MAX_SIZE || q->_back == q->_front)
return 1;
return 0;
}
//整形的插入和删除操作
void test()
{
Queue<int> q;
QueuePush(&q,3);
QueuePush(&q,4);
QueuePush(&q,5);
QueuePush(&q,6);
QueuePush(&q,7);
printf("size = %d\n",QueueSize(&q));
printf("front = %d\n",QueueTop(&q));
printf("back = %d\n",QueueBack(&q));
QueuePop(&q);
QueuePop(&q);
printf("size = %d\n",QueueSize(&q));
printf("front = %d\n",QueueTop(&q));
printf("back = %d\n",QueueBack(&q));
}
//字符型的插入和删除的操作
void test1()
{
Queue<char> q;
QueuePush(&q,'a');
QueuePush(&q,'b');
QueuePush(&q,'c');
QueuePush(&q,'d');
printf("size = %d\n",QueueSize(&q));
printf("front = %c\n",QueueTop(&q));
printf("back = %c\n",QueueBack(&q));
QueuePop(&q);
printf("size = %d\n",QueueSize(&q));
printf("front = %c\n",QueueTop(&q));
printf("back = %c\n",QueueBack(&q));
}
int main()
{
test1();
return 0;
}
【数据结构】队列的公共部分,可以插入任意类型的元素
最新推荐文章于 2024-05-18 23:34:43 发布