目录
一.队列的概念及结构
队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出 FIFO(First In First Out) 入队列:进行插入操作的一端称为队尾 出队列:进行删除操作的一端称为队头
二.队列的实现
1.1.基本结构
队列一般采用链表来实现
2.1.Queue.h
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>
typedef int QDataType;
typedef struct QLsitNode
{
struct QLsitNode* next;
QDataType val;
}QListNode;
typedef struct Queue
{
QListNode* head;
QListNode* tail;
}Queue;
// 初始化队列
void QueueInit(Queue* q);
// 队尾入队列
void QueuePush(Queue* q, QDataType data);
// 队头出队列
void QueuePop(Queue* q);
// 获取队列头部元素
QDataType QueueFront(Queue* q);
// 获取队列队尾元素
QDataType QueueBack(Queue* q);
// 获取队列中有效元素个数
int QueueSize(Queue* q);
// 检测队列是否为空,如果为空返回非零结果,如果非空返回0
int QueueEmpty(Queue* q);
// 销毁队列
void QueueDestroy(Queue* q);
2.2.Queue.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "Queue.h"
// 初始化队列
void QueueInit(Queue* q)
{
q->head = NULL;
q->tail = NULL;
}
// 队尾入队列
void QueuePush(Queue* q, QDataType data)
{
assert(q);
QListNode* new = (QListNode*)malloc(sizeof(QListNode));
if (new == NULL)
{
perror("erro");
exit(-1);
}
new->val = data;
if (q->head == NULL)
{
q->head = new;
q->tail = new;
}
else
{
q->tail->next = new;
q->tail = new;
}
}
// 队头出队列
void QueuePop(Queue* q)
{
assert(q);
assert(!QueueEmpty(q));
QListNode* tmp = q->head;
q->head = q->head->next;
free(tmp);
}
// 获取队列头部元素
QDataType QueueFront(Queue* q)
{
assert(q);
assert(q->head);
return q->head->val;
}
// 获取队列队尾元素
QDataType QueueBack(Queue* q)
{
assert(q);
assert(q->tail);
return q->tail->val;
}
// 获取队列中有效元素个数
int QueueSize(Queue* q)
{
QListNode* cur = q->head;
int size = 0;
while (cur)
{
size++;
cur = cur->next;
}
return size;
}
// 检测队列是否为空,如果为空返回非零结果,如果非空返回0
int QueueEmpty(Queue* q)
{
return q->head == NULL;
}
// 销毁队列
void QueueDestroy(Queue* q)
{
QListNode* cur = q->head;
QListNode* tmp = q->head;
while (cur)
{
tmp = cur;
cur = cur->next;
free(tmp);
}
}
2.3.test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "Stack.h"
#include "Queue.h"
void test()
{
ST s;
StackInit(&s);
StackPush(&s, 1);
StackPush(&s, 2);
StackPush(&s, 3);
StackPush(&s, 4);
printf("元素个数为:%d\n", StackSize(&s));
while (!StackEmpty(&s))
{
printf("%d ", StackTop(&s));
StackPop(&s);
}
}
void test1()
{
Queue q;
QueueInit(&q);
QueuePush(&q, 1);
QueuePush(&q, 2);
QueuePush(&q, 3);
QueuePush(&q, 4);
while (!QueueEmpty(&q))
{
printf("%d ", QueueFront(&q));
QueuePop(&q);
}
printf("\n%d\n", QueueSize(&q));
}
int main()
{
//test();
test1();
return 0;
}