队列
特点
特点:从队尾的位置进行插入数据
从队首的位置进行删除数据
先进的数据先出(FIFO)
顺序队列 - 顺序存储 - 数组
定义 结构体
#define MAX_SIZE 100
typedef int data_t;
typedef struct queue{
data_t data[MAX_SIZE];
int head; //队首的位置
int last; //队尾的位置
}queue_t;
创建队列 - 普通队列
定义一个队列,在堆上分配空间
初始化队列,队首和队尾初始化 - 0
//创建队列
queue_t *create_queue(void){
queue_t *q = NULL;
q = (queue_t *)malloc(sizeof(queue_t));
if(q == NULL){
printf("create_queue malloc failed\n");
return NULL;
}
q->last = 0;
q->head = 0;
return q;
判空队列
last = MAX_SIZE
int empty_queue(queue_t *q){
if(q->last == q->head){
return 1;
}
return 0;
判满队列
last = head
int full_queue(queue_t *q){
return (q->last == MAX_SIZE);
}
入队
判满
将数据存储到last所指向的位置
last++
//入队
int in_queue(queue_t *q, data_t x)
{
//判满
if(full_queue(q)){
printf("queue is full\n");
return -1;
}
//将数据存储到last所指向的位置
q->data[q->last] = x;
//last++
q->last++;
return 0;
}
出队
判空
取出head所指向的位置上的数据
head++
//出队
data_t out_queue(queue_t *q)
{
data_t x;
//判空
if(empty_queue(q)){
printf("queue is empty\n");
return;
}
//取出head所指向的位置上的数据
x = q->data[q->head];
//head++
q->head++;
return x;
}