队列:(queue) 又称FIFO,first input first output 只允许在两端进行操作,尾部插入,头部删除的一个线性表。 队列的作用: 缓存, 匹配输入和输出两种不用的速度. 1.顺序存储 -- 小复杂 使用普通数组实现,发现删除的时候,大量的搬移数据. 我们使用变通的方法: 环形队列 2.链式存储-- 就是使用链表完成FIFO. 判空:phead->next=NULL; 入列:从尾部不断的插入(追加)数据 ph->next=p; ptail=ptail->next;
出列:
q=phead->next; m=q->next; phead->next=m;
下面是他的使用
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node {
int val;
struct node *next;
};
struct node head;
struct node *phead=&head;
struct node *ptail=&head;
void list_queue_init(struct node *phead)
{
phead->next=NULL;
}
void list_queue_push(int val)
{
struct node *p;
p=malloc(sizeof(*p));
p->val=val; p->next=NULL;
ptail->next=p;
ptail=ptail->next;
}
int list_queue_is_empty(struct node *phead)
{
return phead->next == NULL ?1:0;
}
int list_queue_pop(struct node *phead,int *val)
{
if( list_queue_is_empty(phead)==1 ){
return -1;
}
struct node *p=phead->next;
struct node *m=p->next;
if(p->next == NULL){
ptail=phead;
}
phead->next=m;
*val=p->val;
free(p) ;
return 0;
}
int main()
{
struct node *p;
//init
list_queue_init(phead);
//push queue
for(int i=1;i<=10;i++){
list_queue_push(i);
}
int val;
//pop
for(int i=0;i<12;i++){
int ret = list_queue_pop(phead,&val);
if(ret <0){
printf("sorry nothing to pop\n");
break;
}
printf("%d ",val);
}
printf("\n");
return 0;
}