基本操作包括:
初始化
求队长
入队
出队
判队空
判队满
获取队头元素
销毁队
清空队
源代码:
#include<iostream>
#include<stdlib.h>
using namespace std;
#define MAXSIZE 100
typedef int QElemType;
typedef int Status;
typedef struct
{
QElemType* base;
int front;
int rear;
}SqQueue;
bool InitQueue(SqQueue& Q)
{
Q.base = (QElemType*)malloc(MAXSIZE * sizeof(QElemType));
if (!Q.base) return false;
Q.front = Q.rear = 0;
return true;
}
int QueueLength(SqQueue Q)
{
return(MAXSIZE - Q.front + Q.rear)%MAXSIZE;
}
bool EnQueue(SqQueue& Q, QElemType e)
{
if ((Q.rear + 1) % MAXSIZE == Q.front)return false;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXSIZE;
return true;
}
bool DeQueue(SqQueue& Q, QElemType e)
{
if (Q.front == Q.rear)return false;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXSIZE;
printf("%d\n", e);
}
bool QueueEmpty(SqQueue Q)
{
if (Q.front == Q.rear)
return true;
return false;
}
bool QueueFull(SqQueue Q)
{
if ((Q.rear + 1) % MAXSIZE == Q.front)
return true;
return false;
}
Status GetFront(SqQueue Q,QElemType e)
{
if (QueueEmpty(Q))
return false;
e = Q.base[Q.front];
return e;
}
void DestoryQueue(SqQueue& Q)
{
while (&Q.base[Q.front])
{
Q.rear = Q.front+1;
free(&Q.base[Q.rear]);
Q.front = Q.rear;
}
}
bool ClearQueue(SqQueue& Q)
{
if (QueueEmpty(Q))
return true;
Q.front = Q.rear;
}
int main()
{
int lenght;
int e=0;
SqQueue Q;
InitQueue(Q);
EnQueue(Q, 1);
EnQueue(Q, 2);
EnQueue(Q, 3);
EnQueue(Q, 4);
lenght=QueueLength(Q);
printf("%d\n", lenght);
DeQueue(Q, e);
ClearQueue(Q);
lenght = QueueLength(Q);
printf("%d\n", lenght);
DeQueue(Q, e);
}