//队列的链表式实现
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h> //现算表达式,如果为假,向stderr打印出错信息并通过abort终止程序
typedef int QDateType; //定义别名
typedef struct QueueNode//结构体,队列中的元素:值和指向下个元素的指针
{
QDateType val;
struct QueueNode* next;
}QueueNode;
typedef struct Queue //队列
{
QueueNode* head; //头指针
QueueNode* tail; //尾指针
}Queue;
//队列初始化
void QueueInti(Queue* pq)
{
assert(pq); //非空
pq->head = pq->tail = NULL;
}
//队列销毁
void QueueDestory(Queue* pq)
{
assert(pq);
QueueNode* cur = pq->head;
while (cur)
{
QueueNode* next = cur->next;
free(cur);
cur = next;
}
pq->tail = pq->head = NULL;
}
//队尾插入元素
void QueuePush(Queue* pq, QDateType x)
{
assert(pq);
QueueNode* newNode = (QueueNode*)malloc(sizeof(QueueNode));
if (NULL == newNode)
{
printf("malloc error\n");
exit(-1);
}
newNode->val = x;
newNode->next = NULL;
if (pq->tail == NULL)
{
assert(pq->head == NULL);
pq->head = pq->tail = newNode;
}
else
{
pq->tail->next = newNode;
pq->tail = newNode;
}
}
//队首删除元素
void QueuePop(Queue* pq)
{
assert(pq);
assert(pq->head && pq->tail);
if (pq->head->next == NULL)
{
free(pq->head);
pq->head = pq->tail = NULL;
}
else
{
QueueNode* next = pq->head->next;
free(pq->head);
pq->head = next;
}
}
//队列是否为空
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->head == NULL;
}
//取出队首元素-不删除
QDateType QueueFront(Queue* pq)
{
assert(pq);
assert(pq->head);
return pq->head->val;
}
//取出队尾元素-不删除
QDateType QueueBack(Queue* pq)
{
assert(pq);
assert(pq->tail);
return pq->tail->val;
}
//队列中元素数目
int QueueSize(Queue* pq)
{
assert(pq);
QueueNode* cur = pq->head;
int count = 0;
while (cur)
{
cur = cur->next;
count++;
}
return count;
}
int main()
{
Queue q;
QueueInti(&q);
QueuePush(&q, 1);
QueuePush(&q, 2);
QueuePush(&q, 3);
QueuePush(&q, 4);
QueuePush(&q, 5);
QueuePush(&q, 6);
int n1 = QueueSize(&q);
printf("初试元素数目:%d\n", n1); //6
//弹出并删除队首的3个元素:1 2 3,剩下4 5 6
QueuePop(&q);
QueuePop(&q);
QueuePop(&q);
int n2 = QueueSize(&q);
printf("当前元素数目:%d\n", n2); //3
printf("当前队首元素%d\n", QueueFront(&q)); //4
printf("当前队尾元素%d\n", QueueBack(&q)); //6
system("pause");
return 0;
}
C语言实现队列(先进先出)
最新推荐文章于 2024-04-12 10:06:23 发布