编写一个程序,实现链队列的各种基本运算,
(MAXQSIZE = 5),并在此基础上设计一个主程序完成如下功能:
(1)初始化队列 q;
(2)判断队列 q 是否为空;
(3)依次进队列元素 1, 12, -10; (4)出队一个元素,并输出该元素;
(5)输出队列的长度(元素个数);
(6)依次进队元素 13, -12, 10; (7)输出队列长度;
(8)输出出队序列
#include<stdio.h>
#define OK 1
#define ERROR 0
#define MAXSIZE 5
typedef int QElemType;
typedef int Status;
//链队的存储结构
typedef struct QNode
{
QElemType data; //数据域
struct QNode *next; //指针域
}QNode,*QueuePtr;
typedef struct
{
QueuePtr front; //队头指针
QueuePtr rear; //队尾指针
}LinkQueue;
//链队的初始化
Status InitQueue(LinkQueue &Q)
{
Q.front = Q.rear = new QNode; //生成新结点作为队头结点,队头队尾指针指向此结点
Q.front->next = NULL; //头结点的指针域置空
return OK;
}
//判空
Status QueueEmpty(LinkQueue Q)
{
if (Q.front == Q.rear) return ERROR;
else return OK;
}
//入队
Status EnQueue(LinkQueue &Q, QElemType e)
{
QueuePtr p;
p = new QNode; //生成新结点
p->data = e; //赋值e
p->next = NULL; //插入队尾,后插法
Q.rear->next = p;
Q.rear = p;
return OK;
}
//出队
Status DeQueue(LinkQueue &Q, QElemType &e)
{
if(Q.front == Q.rear) return ERROR; //判空
QueuePtr p;
p = Q.front->next; //p标记队头结点
e = p->data; //队头元素赋给e
Q.front->next = p->next;
if (Q.rear == p)Q.rear = Q.front; //最后一个元素被删除
delete p; //删除队头结点
return OK;
}
//求队的长度
int QueueLength(LinkQueue Q)
{
int n = 0; //记录长度
if (Q.front == Q.rear) return ERROR; //判空
while (Q.front != Q.rear)
{
Q.front = Q.front->next; //顺沿
n++;
}
return n;
}
int main()
{
LinkQueue Q; QElemType e; int n = 3;
InitQueue(Q); //初始化队Q
//判空
printf("空为0,不空为1:%d\n", QueueEmpty(Q));
//入队
printf("依次进队元素:-1 12 10\n");
scanf_s("%d", &e);
EnQueue(Q, e);
for (int i = 0; i < n-1; i++)
{
scanf_s("%d", &e);
EnQueue(Q, e);
}
//出队
printf("出队一个元素\n");
DeQueue(Q, e);
printf("%d\n", e);
//求队长
printf("队列长度:%d\n", QueueLength(Q));
//入队
printf("依次进队元素 -3 2 -10\n");
for (int i = 0; i < 3; i++)
{
scanf_s("%d", &e);
EnQueue(Q, e);
}
printf("队列长度:%d\n", QueueLength(Q));
//出队并输出
while (QueueEmpty(Q))
{
DeQueue(Q,e);
printf("%5d", e);
}
}