typedef int QElemType;
typedef struct QNode
{
QElemType data;
QNode *next;
}*QueuePtr;
struct LinkQueue
{
QueuePtr front, rear;//队头、队尾指针
};
void InitQueue(LinkQueue &Q)
{
//构造一个空队列
if (!(Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode))))
{
exit(OVERFLOW);
}
Q.front->next = NULL;
}
void DestroyQueue(LinkQueue &Q)
{
//销毁队列
while (Q.front)
{
Q.rear = Q.front->next;
free(Q.front);
Q.front = Q.rear;
}
}
void ClearQueue(LinkQueue &Q)
{
//清空队列
QueuePtr p, q;
Q.rear = Q.front;
p = Q.front->next;
Q.front->next = NULL;
while (p)
{
q = p;
p = p->next;
free(q);
}
}
Status QueueEmpty(LinkQueue Q)
{
//判断空队列
if (Q.front->next == NULL)
return TRUE;
else
return FALSE;
}
int QueueLength(LinkQueue Q)
{
//求队列的长度
int i = 0;
QueuePtr p;
p = Q.front;
while (Q.rear != p)
{
i++;
p = p->next;
}
return i;
}
Status GetHand(LinkQueue Q, QElemType &e)
{
//若队列不空,返回队头元素,并返回OK,否则返回ERROR
QueuePtr p;
if (Q.front == Q.rear)
{
return ERROR;
}
p = Q.front->next;
e = p->data;
return OK;
}
void EnQueue(LinkQueue &Q, QElemType e)
{
//插入元素e为Q的新的队尾元素
QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
if (!p)//存储分配失败
{
exit(ERROR);
}
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
}
Status DeQueue(LinkQueue &Q, QElemType &e)
{
//删除队头元素,用e返回其值,并返回OK,否则返回ERROR
QueuePtr p;
if (Q.front == Q.rear)
{
return ERROR;
}
p = Q.front->next;
e = p->data;
Q.front->next = p->next;
if (Q.rear == p)
{
Q.rear = Q.front;
}
free(p);
return OK;
//if (Q.front == Q.rear)//无元素
//{
// return ERROR;
//}
//else if (Q.front->next == Q.rear)//只有一个元素,即队尾元素指向那个元素
//{
// p = Q.rear;
// Q.rear = Q.front;
// free(p);
//}
//else//队内有两个及以上的元素
//{
// p = Q.front->next;
// e = p->data;
// Q.front->next = p->next;
// free(p);
// return OK;
//}
}
void QueueTraverse(LinkQueue Q, void(*vi)(QElemType))
{
//从队头到队尾依次对队列Q中每个元素调用函数vi()
QueuePtr p;
p = Q.front->next;
while (p)
{
vi(p->data);
p = p->next;
}
printf("\n");
}
void print1(QElemType i)
{
printf("%d", i);
}
void main()
{
int i;
QElemType d;
LinkQueue q;
InitQueue(q);
printf("成功的构造了一个空队列!\n");
printf("是否空队列?%d(1:空 0:否)",QueueEmpty(q));
printf("队列的长度为%d\n", QueueLength(q));
EnQueue(q, -5);
EnQueue(q, 5);
EnQueue(q, 10);
printf("插入3个元素(-5,5,10)后,队列的长度为%d\n", QueueLength(q));
printf("是否是空队列?%d(1:空 2:否)", QueueEmpty(q));
printf("队列的元素依次为");
QueueTraverse(q, print1);
i = GetHand(q, d);
if (i == OK)
{
printf("队头元素是:%d\n", d);
}
DeQueue(q, d);
printf("删除了队头元素%d\n", d);
i = GetHand(q, d);
if (i == OK)
{
printf("新的队头元素是:%d\n", d);
}
ClearQueue(q);
printf("清空队列后,Q.front = %u Q.rear = %u Q.front->next = %u\n", q.front, q.rear, q.front->next);
DestroyQueue(q);
printf("销毁队列后,Q.front = %u Q.rear = %u Q.front->next = %u\n", q.front, q.rear, q.front->next);
}
程序运行结果: