本节主要实现了基本的队列顺序表示,如有错误欢迎指正!
#include <iostream>
using namespace std;
#define QUEUE_INIT_SIZE 10 //队列的初始开辟空间
#define QUEUE_INCREMENT_SIZE 2//队列满后,每次增加的空间长度
typedef int DataType;
struct SqQueue
{
DataType* base;
int rear;//队列长度
int queuesize;//队列开辟空间
};
//队列的初始化;
bool SqQueueInit(SqQueue& Q)
{
Q.base = (DataType*)malloc(sizeof(DataType));
if (!Q.base)
{
cout << "Q.base malloc error" << endl;
exit(0);
}
Q.rear = 0;
Q.queuesize = QUEUE_INIT_SIZE;
return true;
}
//销毁队列;
void SqQueueDestroy(SqQueue& Q)
{
free(Q.base);
Q.base = NULL;
Q.rear = 0;
Q.queuesize = 0;
}
//存储长度清零;
void SqQueueClear(SqQueue& Q)
{
Q.rear = 0;
}
//队列是否为空
bool SqQueueEmpty(SqQueue Q)
{
if (!Q.rear)
return true;
else
return false;
}
//队列长度
int SqQueueLength(SqQueue Q)
{
return Q.rear;
}
void SqQueueGetHead(SqQueue Q, DataType& e)
{
if (Q.rear)
{
e = Q.base[0];
}
}
//入队
bool SqQueueInsert(SqQueue& Q,DataType e)
{
if (Q.rear >= Q.queuesize)
{
Q.base = (DataType*)realloc(Q.base,(Q.queuesize + QUEUE_INCREMENT_SIZE) * sizeof(DataType));
if (!Q.base)
{
cout << "increment malloc error" << endl;
exit(0);
}
Q.rear = Q.queuesize;//重新赋予存储长度;
Q.queuesize += QUEUE_INCREMENT_SIZE;//开辟空间长度增加;
}
Q.base[Q.rear++] = e;
return true;
}
//出队,注意这里出队队头元素后要挪动后边的元素
bool SqQueueDelete(SqQueue& Q, DataType& e)
{
if (!Q.rear)
return false;
e = Q.base[0];
for (int i = 0; i < Q.rear - 1; i++)
{
Q.base[i] = Q.base[i + 1];
}
Q.rear--;
return true;
}
//遍历队列
void SqQueueTraverse(SqQueue Q,void(*visit)(DataType*))
{
while (Q.rear)
{
visit(Q.base++);
Q.rear--;
}
cout << endl;
}
void visit(DataType* c)
{
cout << " " << *c;
}
void main()
{
DataType e0;
SqQueue Q;
SqQueueInit(Q);
cout << "Q的长度为:" << SqQueueLength(Q) << endl;
for (int i = 1; i <= 5; i++)
{
SqQueueInsert(Q,i);
}
cout << "插入元素后,队列为:";
SqQueueTraverse(Q,visit);
cout << "此时队列的长度为:" << SqQueueLength(Q) << endl;
SqQueueDelete(Q,e0);
cout << "出队元素为:" << e0 << endl;
cout << "队列元素为:";
SqQueueTraverse(Q,visit);
cout << "出队后,队列的长度为:" << SqQueueLength(Q) << endl;
SqQueueGetHead(Q,e0);
cout << "此时队列的队头为:" << e0 << endl;
SqQueueClear(Q);
cout << "队列清空后,队列的长度为:" << SqQueueLength(Q) << endl;
system("pause");
}
通过程序发现,顺序存储结构存在的缺陷,即出队的时候需要整体移动队列的元素!