先进先出的队
文章目录
- 队列特点
- 队列实现
队列特点
先进先出,后进后出
队列实现
queue.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"Queue.h"
//初始化
void QueInit(Queue* pq)
{assert(pq);pq->head = NULL;pq->tail = NULL;pq->size = 0;
}
//入队,一定在队尾入
void QuePush(Queue* pq, QDataType x)
{assert(pq);//开辟地址Qnode* newnode = (Qnode*)malloc(sizeof(Qnode));//开辟失败处理if (newnode==NULL){perror("malloc error");return;}newnode->data = x;newnode->next = NULL;if (pq->head==NULL){//确定是不是为空,不为空就报错,说明tail和head有错误assert(pq->tail == NULL);pq->head = pq->tail = newnode;}else{pq->tail->next = newnode;pq->tail = newnode;} pq->size++;
}
//出队,一定在队头出
void QuePop(Queue* pq)
{assert(pq);assert(!QueEmpty(pq));Qnode* next = pq->head->next;free(pq->head);pq->head = next;
}
//大小
int QueSize(Queue* pq)
{assert(pq);return pq->size;
}
//销毁
void QueDistory(Queue* pq)
{assert(pq);//要记得指向head,不要把pq直接拿来用,pq只是存节点的一个结构Qnode* cur = pq->head;while (cur != NULL){Qnode* next = cur->next;free(cur);cur = next;}pq->head = pq->tail = NULL;pq->size = 0;
}
//判断是否空了
bool QueEmpty(Queue* pq)
{assert(pq);//头为空,那这个队就是空的return pq->head == NULL;
}
//出栈展示
void QueShow(Queue* pq)
{assert(pq);Qnode* cur=pq->head;while (cur){printf("%d", cur->data);cur = cur->next;}
}
//返回前面的值
QDataType QueFront(Queue* pq)
{assert(pq);return pq->head->data;
}
//返回后面的值
QDataType QueBack(Queue* pq)
{assert(pq);return pq->tail->data;
}
test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"Queue.h"
void Quequetest()
{Queue pq;QueInit(&pq);QuePush(&pq, 1);QuePush(&pq, 2);QuePush(&pq, 3);QueShow(&pq);QueDistory(&pq);}
int main()
{Quequetest();return 0;
}
queue.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>typedef int QDataType;
typedef struct QueueNode
{struct QueueNode* next;QDataType data;
}Qnode;//定义节点,创造标记点
typedef struct Queue
{Qnode* head;//标记队列的头Qnode* tail;//标记队列的尾int size;
}Queue;//存储指针指向节点//先进先出
//后进后出
//链表队列
//
//初始化
void QueInit(Queue* ps);
//入队,一定在队尾入
void QuePush(Queue* ps, QDataType x);
//出队,一定在队头出
void QuePop(Queue* ps);
//大小
int QueSize(Queue* ps);
//销毁
void QueDistory(Queue* ps);
//判断是否空了
bool QueEmpty(Queue* ps);
//出栈展示
void QueShow(Queue* ps);
//访问对头数据
QDataType QueFront(Queue* ps);
//访问队尾数据
QDataType QueBack(Queue* ps);