我与代码的日常:队列的基本操作(C语言版)
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int QDataType;
//链表节点
typedef struct QNode
{
QDataType val;
struct QNode* next;
}QNode;
//队列
typedef struct Queue
{
QNode* front; //指向队首元素
QNode* rear; //指向队尾元素
int size;
} Queue;
//初始化
void QueueInit(Queue* queue)
{
queue->front = queue->rear = NULL;
queue->size = 0;
printf("队列初始化成功!\n");
}
//销毁
void QueueDestroy(Queue* queue)
{
QNode* next;
for (QNode*cur = queue->front; cur != NULL; cur = next)
{
next = cur->next;
free(cur);
}
queue->front = queue->rear = NULL;
queue->size = 0;
printf("销毁成功!\n");
}
//增加元素
void QueuePush(Queue* queue, QDataType val)
{
QNode* node = (QNode*)malloc(sizeof(QNode));
node->val = val;
node->next = NULL;
queue->size++;
if (queue->rear == NULL)
{
//队列起初为空
queue->front = queue->rear = node;
}
else
{
queue->rear ->next= node;
queue->rear = node;
queue->rear->next = NULL;
}
printf("%d入队成功!\n", node->val);
}
//删除
void QueuePop(Queue* queue)
{
assert(queue->size > 0);
queue->size--;
QNode* old_front = queue->front;
queue->front = queue->front->next;
free(old_front);
if (queue->front == NULL)
{
printf("队列为空,删除失败!\n");
}
}
//返回队首元素
QDataType QueueFront(Queue* queue)
{
assert(queue->size > 0);
return queue->front->val;
}
//返回队列元素个数
int QueueSize(Queue* queue)
{
return queue->size;
}
//打印队列元素
void QueuePrint(Queue* queue)
{
assert(queue->size > 0);
QNode* cur = queue->front;
while (cur!=NULL)
{
printf("%d ", cur->val);
cur = cur->next;
}
}
void Test()
{
Queue queue;
QueueInit(&queue);
QueuePush(&queue, 1);
QueuePush(&queue, 2);
QueuePush(&queue, 3);
QueuePush(&queue, 4);
QueuePush(&queue, 5);
QueuePrint(&queue);
printf("\n删除一个元素: ");
QueuePop(&queue);
QueuePrint(&queue);
printf("此时队首元素为: %d\n", QueueFront(&queue));
printf("\n此时队列里元素个数为: %d\n", QueueSize(&queue));
QueueDestroy(&queue);
}
int main()
{
Test();
system("pause");
return 0;
}
运行结果: