//队列的链表式实现
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h> //现算表达式,如果为假,向stderr打印出错信息并通过abort终止程序
typedef int QDateType; //定义别名
int MaxSize = 8; //定义别名
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;
}
//队首删除元素
QueueNode* QueuePop(Queue* pq)
{
assert(pq);
assert(pq->head && pq->tail);
QueueNode* delete = NULL;
if (pq->head->next == NULL)
{
delete = pq->head;
free(pq->head);
pq->head = pq->tail = NULL;
}
else
{
QueueNode* next = pq->head->next;
delete = pq->head;
free(pq->head);
pq->head = next;
}
return delete;
}
//队列是否为空
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;
}
//队尾插入元素
void QueuePush(Queue* pq, QDateType x)
{
assert(pq);
if(QueueSize(pq) == MaxSize){
QueueNode* wq = QueuePop(pq);
if(wq == NULL){
printf("当前队列为空");
}else{
printf("出队列元素:%d\n" , wq->val);
}
}
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 printQueue(Queue* pq)
{
assert(pq);
printf("\n输出队列中所有数据内容:");
while (QueueSize(pq) >0)
{
QueueNode* q= QueuePop(pq);
printf("%d",q->val);
}
printf("\n");
}
int main()
{
Queue q;
QueueInti(&q);
printf("输入-1结束当前输入。\n");
while (true)
{
int a;
printf("请输入入队数:");
scanf("%d",&a);
if(a == -1){
printf("结束时队列数据大小:%d",QueueSize(&q));
printQueue(&q);
return 0;
}
QueuePush(&q, a);
}
return 0;
}
使用c语言实现队列,最多8个数据。