#include<stdio.h>
#include<stdlib.h>
#include<memory.h>
//线性队列
#define MAX_QUEUE_SIZE 5
typedef struct {
char data;
int data_len;
} data_info_t;
typedef struct test_linear_queue {
data_info_t data_info[MAX_QUEUE_SIZE];
int rear; //后
int front; //前
} linear_queue_t;
//创建队列
linear_queue_t * test_creat_linear_queue() {
linear_queue_t *linear_queue = (linear_queue_t *)malloc(sizeof(linear_queue_t));
if(NULL == linear_queue) {
return NULL;
}
memset(linear_queue,0,sizeof(linear_queue_t));
linear_queue->front = linear_queue->rear = MAX_QUEUE_SIZE-1;
return linear_queue;
}
int test_add_node_to_linear_queue(linear_queue_t *queue,data_info_t *item) {
//判满
if(queue->front == (queue->rear+1)%MAX_QUEUE_SIZE)
{
printf("queue full\n");
return -1;
}
queue->rear = (++queue->rear) % MAX_QUEUE_SIZE;
queue->data_info[queue->rear].data = item->data;
queue->data_info[queue->rear].data_len = item->data_len;
printf("rear = %d add ok %p data %d,data_len %d \n",queue->rear,item,item->data,item->data_len);
return 0;
}
void show_linear_queue(linear_queue_t *queue)
{
printf("===================\n");
for(int i = 0 ;i<MAX_QUEUE_SIZE;i++)
{
printf("data %d,data_len %d\n",queue->data_info[i].data,queue->data_info[i].data_len);
}
printf("===================\n");
}
int test_out_node_to_linear_queue(linear_queue_t *queue,data_info_t *item)
{
//判空
if(queue->front == queue->rear)
{
printf("queue is empty\n");
return -1;
}
//从头拿
queue->front = (++queue->front) % MAX_QUEUE_SIZE;
item->data = queue->data_info[queue->front].data;
item->data_len = queue->data_info[queue->front].data_len;
//memset(&queue->data_info[queue->front],0,sizeof(data_info_t));
return 0;
}
int main() {
linear_queue_t *queue = NULL;
queue = test_creat_linear_queue();
if(NULL == queue)
{
printf("queue creat error\n");
return -1;
}
//入队添加
data_info_t data_info_item;
//循环添加
for(int i = 0;i < MAX_QUEUE_SIZE;i++)
{
data_info_item.data = i+1;
data_info_item.data_len = i+1;
test_add_node_to_linear_queue(queue,&data_info_item);
}
// 出队删除
if(!test_out_node_to_linear_queue(queue,&data_info_item))
printf("out ok ,data %d,data_len %d \n",data_info_item.data,data_info_item.data_len);
if(!test_out_node_to_linear_queue(queue,&data_info_item))
printf("out ok ,data %d,data_len %d \n",data_info_item.data,data_info_item.data_len);
//读取两次后,打印队列所有节点
show_linear_queue(queue);
//再加一个 然后再打印
data_info_item.data = 99;
data_info_item.data_len = 99;
test_add_node_to_linear_queue(queue,&data_info_item);
data_info_item.data = 100;
data_info_item.data_len = 100;
test_add_node_to_linear_queue(queue,&data_info_item);
show_linear_queue(queue);
if(!test_out_node_to_linear_queue(queue,&data_info_item))
printf("out ok ,data %d,data_len %d \n",data_info_item.data,data_info_item.data_len);
show_linear_queue(queue);
for(int i = 0;i<MAX_QUEUE_SIZE;i++)
{
if(!test_out_node_to_linear_queue(queue,&data_info_item))
printf("out ok ,data %d,data_len %d \n",data_info_item.data,data_info_item.data_len);
}
return 0;
}
可以看出是顺序拿出