一、队列理论
1.队列是一种受约束的线性表,一端插入,另一端移除数据,数据先进先出
二、程序demon
#include<stdio.h>
#include<stdlib.h>
#define QUEUE_SIZE 4
typedef struct{
char *data[QUEUE_SIZE];//存放指针的数组,队列大小是QUEUE_SIZE-1
int prev;
int next;
}queue_t;
//1.初始化一个队列
queue_t *create_queue()
{
queue_t *p=malloc(sizeof(queue_t));
p->prev=p->next=0;
return p;
}
//2.判断队列是否为空 空-返回1 非空-返回0
int queue_empty(queue_t *p)
{
return p->prev == p->next;
}
//3.判断队列是否为满 满-返回1 非满-返回0
int queue_full(queue_t *p)
{
if((p->next+1) % QUEUE_SIZE==p->prev )//队尾加1等于队首认为存满
return 1;
else
return 0;
}
//3.向队列push一个数据
void queue_push(queue_t *p,char *data)
{
if(1==queue_full(p))
{
printf("队列满\n");
return ;
}
p->data[p->next] = data;
printf("插入数据:next = %d \t data is %s\n",p->next,data);
p->next=(p->next+1)%(QUEUE_SIZE);//取余,确保队尾插入数据后可以循环,实现先进先出
}
char *OutQueue(queue_t *p)
{
char* x;
x="queue is empty";
if(queue_empty(p))
{
//printf("queue is empty\n");
return x;
}
x = p->data[p->prev];
printf("移除数据:p->prev is %d \t",p->prev);
p->prev = (p->prev + 1) % QUEUE_SIZE;取余,确保队首移出数据后可以循环,实现先进先出
return x;
}
int main()
{
queue_t *queue = create_queue();
queue_push(queue,"hello");
queue_push(queue,"world");
queue_push(queue,"!");
printf("msg is:%s\n",OutQueue(queue));
printf("msg is:%s\n",OutQueue(queue));
printf("msg is:%s\n",OutQueue(queue));
printf("msg is:%s\n",OutQueue(queue));
queue_push(queue,"hello");
queue_push(queue,"world");
queue_push(queue,"!");
queue_push(queue,"how");
queue_push(queue,"are");
queue_push(queue,"you");
printf("msg is:%s\n",OutQueue(queue));
printf("msg is:%s\n",OutQueue(queue));
printf("msg is:%s\n",OutQueue(queue));
printf("msg is:%s\n",OutQueue(queue));
return 0;
}
运行结果: