队列是后插前出的数据结构,先进先出
以下代码:
#include<stdio.h>
#include<stdlib.h>
//队列是只许在一端进行插入,另一端进行删除操作
//是一个先进先出的线性表(后插,前出)
//链队列
typedef struct QNode {
char data;
struct QNode *next;
}QNode,*QueuePrt;
typedef struct {
QueuePrt front, rear;
}LinkQueue;
//front指向头结点,rear(队尾指针)指向终端结点,空队列时,front和rear都指向头结点
initQueue(LinkQueue*q) {
q->front = q->rear = (QueuePrt)malloc(sizeof(QNode));
q->front->next = 0;
}
//入队列操作
InsertQueue(LinkQueue*q, int e) {
QueuePrt p;
p = (QueuePrt)malloc(sizeof(QNode));
if (!p)
exit(0);//如果p没有赋空间成功,则退出程序
p->data = e;
p->next = 0;
q->rear->next = p;
q->rear= p;
}
//出队列操作
DeleteQueue(LinkQueue*q, char*e) {
//注意字符的声明
QueuePrt p;
if (q->front == q->rear) {
return;
}
p = q->front->next;
if(p)*e = p->data;//
q->front->next = p->next;
if (q->rear == p)
q->rear = q->front;
free(p);
}
DestroyQueue(LinkQueue*q) {
while (q->front) {
q->rear = q->front->next;
free(q->front);
q->front = q->rear;
}
}
//队列的顺序存储结构不是很灵活,队列的数量有限制,容易造成数组越界的情况。
//为保证队列的空间充分利用,每次出队列时需要让数组里的元素整体前移一格,或指针后移一格
//数组存放队列的最好方式是 循环队列(顺序表模拟的循环)
#define MAXSIZE 20
typedef struct {
char*base;
int front;
int rear;
}cycleQueue;
void initCQueue(cycleQueue*q) {
q->base = (char*)malloc(MAXSIZE * sizeof(char));
if (!q->base)
exit(0);
q->front = q->rear = 0;
}
void InsertCQueue(cycleQueue*q, char e) {
if ((q->rear + 1) % MAXSIZE == q->front)
return;//表示队列已满
q->base[q->rear] = e;
q->rear = (q->rear + 1) % MAXSIZE;//指向下一个地址
}
DleteCQueue(cycleQueue*q, char*e) {
if (q->front = q->rear)
return;
*e = q->base[q->front];
q->front = (q->front + 1) % MAXSIZE;
}
int main() {
char c, e;
LinkQueue q;
initQueue(&q);//将队列初始化,为队列赋上空间,并让队头和队尾相等并等于零
printf("输入要进队列的字符:");
scanf("%c", &c);
while (c != '\n') {
InsertQueue(&q, c);//在队列的后面插入c
scanf("%c", &c);
}
while (q.rear != q.front) {
DeleteQueue(&q, &e);
printf("%c ", e);
}
printf("\n");
return 0;
}