赞
踩
队列是先入先出的,即先入队的数据先出队
下面程序是队列的链式存储结构的实现,具有入队,出队,销毁队列的的功能
#include <stdio.h>
#include <stdlib.h>
#define Ok 1
#define ERROR 0
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 *s) {
s->front = s->rear = (QueuePtr) malloc(sizeof(QNode));
if (!s->front) {
printf("初始化队列错误");
exit(-1);
}
s->front->next = NULL;
return Ok;
}
// 插入到队列
Status InsertQueue(LinkQueue *s, QElemType e) {
QueuePtr p;
p = (QueuePtr) malloc(sizeof(QNode));
if (!p) {
printf("插入队列失败");
exit(-1);
}
p->data = e;
p->next = NULL;
s->rear->next = p;
s->rear = p;
return Ok;
}
// 元素出队列
Status DeQueue(LinkQueue *s, int *e) {
QueuePtr p;
if (s->front == s->rear) {
return ERROR;
}
p = s->front->next;
*e = p->data;
s->front->next = p->next;
if (s->rear == p) {
s->rear = s->front;
}
free(p);
return Ok;
}
// 销毁队列
Status DestoryQueue(LinkQueue *s) {
while (s->front) {
s->rear = s->front->next;
free(s->front);
s->front = s->rear;
}
return Ok;
}
int main() {
int n, tmp, num;
QueuePtr s;
InitQueue(s);
printf("请输入要入队列元素的个数:");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("请输入第 %d 个值:", i + 1);
scanf("%d", &tmp);
InsertQueue(s, tmp);
}
for (int j = 0; j < n; j++) {
DeQueue(s, &num);
printf("%d\t", num);
}
DestoryQueue(s);
return 0;
}
程序运行结果:
输入要入队列元素的个数为6,依次输入4,5,6,7,2,3,结果输出为4 5 6 7 2 3
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。