任务描述
基于链队列完成初始化、入队、出队、取队头元素和求队列元素个数操作
(1)其中基本操作的定义参照教材抽象数据类型ADT LinkQueue的定义。
(2)考虑实际应用中用户最常用的功能,本程序只封装队列初始化、入队、出队、取队头元素和销毁队列的操作。
相关知识
队列的类型定义
队列的逻辑结构
链队列的链式存储结构
编程要求
1.根据函数原型的定义,编写函数实现功能。
2.在主函数的相关位置进行函数调用(主函数的注释语句中标明了需要调用的函数功能,)
3.最后执行“自测运行”或“评测”
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
typedef struct QNode {
ElemType data;
struct QNode *next;
} QNode, *QueuePtr;
typedef struct {
QueuePtr front;
QueuePtr rear;
} LinkQueue;
void InitQueue_L(LinkQueue *pQ) {
pQ->front = pQ->rear = (QueuePtr)malloc(sizeof(QNode));
if (!pQ->front) exit(OVERFLOW);
pQ->front->next = NULL;
}
Status EnQueue_L(LinkQueue *pQ, ElemType e) {
QueuePtr newNode = (QueuePtr)malloc(sizeof(QNode));
if (!newNode) return ERROR;
newNode->data = e;
newNode->next = NULL;
pQ->rear->next = newNode;
pQ->rear = newNode;
return OK;
}
Status DeQueue_L(LinkQueue *pQ, ElemType *pe) {
QueuePtr p = pQ->front->next;
if (pQ->front == pQ->rear) return ERROR;
*pe = p->data;
pQ->front->next = p->next;
if (pQ->rear == p) pQ->rear = pQ->front;
free(p);
return OK;
}
Status GetHead_L(LinkQueue Q, ElemType *pe) {
if (Q.front == Q.rear) return ERROR;
*pe = Q.front->next->data;
return OK;
}
void DestroyQueue_L(LinkQueue *pQ) {
while (pQ->front) {
pQ->rear = pQ->front->next;
free(pQ->front);
pQ->front = pQ->rear;
}
}
int main() {
int rc, n, i;
ElemType e;
LinkQueue Q;
//请调用初始化函数
InitQueue_L(&Q);
printf("请输入要入队的元素数量: ");
scanf("%d", &n); //输入入队元素个数n
for (i = 1; i <= n; i++) { //创建队列的本质是反复的入栈操作
scanf("%d", &e);
rc = EnQueue_L(&Q, e); //请调用入队函数
if (rc != OK) {
printf("Failed to enqueue element %d\n", e);
continue;
}
printf("e=%d is enqueued\n", e);
}
for (i = 1; i <= n; i++) {
printf("**DeQueue**");
// Dequeue the element
rc = DeQueue_L(&Q, &e); //请调用出队函数
if (rc != OK) {
printf("\nQueue is Empty\n");
} else {
printf("\ne=%d is dequeued\n", e);
}
printf("**GetHead**");
// Get the head element
rc = GetHead_L(Q, &e); //请调用获取队头元素函数
if (rc != OK) {
printf("\nQueue is Empty\n");
} else {
printf("\nThe Head Element is %d\n", e);
}
}
//请调用销毁队列函数
DestroyQueue_L(&Q);
return 0;
}
2202

被折叠的 条评论
为什么被折叠?



