测试截图:
源代码:
//测试环境:VS2015
//
//头文件
#include "stdafx.h"
#include<stdlib.h>
#include<stdio.h>
//宏定义
#define OVERFLOW -2
#define OK 1
#define ERROR 0
//定义节点结构体
typedef struct QNode
{
int data;
struct QNode *next;
}QNode,*QueuePtr;
//定义链式队列结构体
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
int initQueue(LinkQueue &Q)
{
//构造一个空队列Q
Q.front = (QueuePtr)malloc(sizeof(QNode));
if (!Q.front)exit(OVERFLOW);
Q.front->next = NULL;
Q.rear = Q.front;
return OK;
}
//销毁队列
int destroyQueue(LinkQueue &Q)
{
while (Q.front)
{
Q.rear = Q.front->next;
free(Q.front);
Q.front = Q.rear;
}
return OK;
}
//清空队列
int clearQueue(LinkQueue &Q)
{
Q.front = Q.rear;
return OK;
}
//判断队列是否为空
bool queueEmpty(LinkQueue Q)
{
return Q.front == Q.rear;
}
//返回队列中的元素个数
int queueLength(LinkQueue &Q)
{
int i = 0;
for (QueuePtr p = Q.front->next; p != NULL; p = p->next)
{
i++;
}
return i;
}
//返回队列头节点的元素
int getHead(LinkQueue Q, int &e)
{
//若队列非空,则返回队列头节点的元素
if (queueEmpty(Q))return ERROR;
e = Q.front->next->data;
return OK;
}
//遍历
int visit(int e)
{
printf("%d ", e);
return OK;
}
//反序输出
int queueTraverse(LinkQueue &Q,int (*visit)(int))
{
for (QueuePtr p = Q.front->next; p!=NULL; p = p->next)
{
visit(p->data);
}
return OK;
}
//插入元素到队列尾
int insertQueue(LinkQueue &Q,int e)
{
//插入元素e为队列的新的队尾元素
QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
if (!p)exit(OVERFLOW);
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return OK;
}
//在队列头删除元素
int deleteQueue(LinkQueue &Q,int &e)
{
if (Q.front == Q.rear)return ERROR;
QueuePtr p = Q.front->next;
e = p->data;
Q.front->next = p->next;
if (p == Q.rear)Q.rear = Q.front;
free(p);
return OK;
}
int outputInformaton(LinkQueue Q)
{
printf_s("输出队列中的各个元素...\n");
queueTraverse(Q, visit);
printf_s("\n");
printf_s("目前队列中的元素个数为:%d\n", queueLength(Q));
return OK;
}
int main()
{
LinkQueue Q;
initQueue(Q);
printf("请输入...\n");
while (true)
{
int e;
scanf_s("%d", &e);
if (e == 1234)break;
insertQueue(Q, e);
}
outputInformaton(Q);
int e;
printf_s("在队头删除元素...\n");
deleteQueue(Q, e);
printf_s("在队头删除的元素是:%d\n", e);
outputInformaton(Q);
printf_s("在队尾插入元素:");
scanf_s("%d", &e);
insertQueue(Q, e);
outputInformaton(Q);
getHead(Q, e);
printf_s("返回目前的对头元素:%d\n", e);
printf_s("清空队列...\n");
clearQueue(Q);
if (queueEmpty(Q))printf_s("队列目前是空的\n");
else
{
printf_s("队列目前不是空的\n");
}
printf("请输入...\n");
while (true)
{
int e;
scanf_s("%d", &e);
if (e == 1234)break;
insertQueue(Q, e);
}
outputInformaton(Q);
printf_s("销毁队列...\n");
destroyQueue(Q);
if (queueEmpty(Q))printf_s("队列目前是空的\n");
else
{
printf_s("队列目前不是空的\n");
}
return 0;
}