队列的实现可以看成一种特殊的链表的实现,所以和链表的逻辑几乎一样,就不再过多讲述
声明部分queue.h:
#pragma once
#include <stdio.h>
#include <stdlib.h>
typedef int QueueDataType ;
typedef struct QueueNode
{
struct QueueNode* next;
QueueDataType data;
}node;
typedef struct Queue
{
node* head;
node* tail;
}QE;
void QueueInit(QE* qu);
void QueueDestroy(QE* qu);
void QueuePush(QE* qu, QueueDataType x);
void QueuePop(QE* qu);
QueueDataType QueueFront(QE* qu);
int QueueSize(QE* qu);
实现部分queue.c:
初始化函数:
void QueueInit(QE* qu)
{
assert(qu);
qu->head = qu->tail = NULL;
}
销毁函数:
void QueueDestroy(QE* qu)
{
assert(qu);
node* cur = qu->head;
while (cur)
{
node* del = cur;
cur = cur->next;
free(del);
}
qu->head = qu->tail = NULL;
}
入队函数:
void QueuePush(QE* qu, QueueDataType x)
{
assert(qu);
//这里的逻辑和链表的新增节点一样
node* newnode = (node*)malloc(sizeof(node));
if (newnode == NULL)
{
printf("malloc fail");
exit(-1);
}
newnode->data = x;
newnode->next = NULL;
//这里需要单独判断是否为空,如果为空就直接指向新节点
if (qu->head == NULL)
{
qu->tail = qu->head = newnode;
}
else//队中有节点
{
qu->tail->next = newnode;
qu->tail = newnode;
}
}
出队函数:
void QueuePop(QE* qu)
{
assert(qu);
assert(qu->head != NULL);
if (qu->head->next == NULL)//判断队中是否只有一个节点
{
free(qu->head);
qu->tail = NULL;
qu->head = NULL;
}
else
{
node* newhead = qu->head->next;
free(qu->head);
qu->head = newhead;//最后改变头指针指向
}
}
获取对头元素函数:
QueueDataType QueueFront(QE* qu)
{
assert(qu);
assert(qu->head != NULL);
return qu->head->data;
}
获取队大小函数:
int QueueSize(QE* qu)
{
assert(qu);
node* cur = qu->head;
int count = 0;
while (cur)
{
count++;
cur = cur->next;
}
return count;
}
测试部分test.c:
#define _CRT_SECURE_NO_WARNINGS
#include "queue.h"
int main()
{
QE queue;
QueueInit(&queue);
QueuePush(&queue, 1);
QueuePush(&queue, 2);
QueuePush(&queue, 3);
while (queue.head != NULL)
{
printf("%d ", QueueFront(&queue));
QueuePop(&queue);
}
QueueDestroy(&queue); // 销毁队列,释放内存
return 0;
}
阿里嘎多!