链队列 通用链表实现
通过list_head 的单链表实现链队列
//头文件
#ifndef QUEUE_H_INCLUDED
#define QUEUE_H_INCLUDED
#define list_entry(type,pos,member) \
(type *)((char *)pos-(int)(&((type *)0)->member))
typedef struct list_h{
struct list_h *next;
}list_head;
typedef struct queue{
list_head *prev,*rear;
}Queue;
void init(Queue *h);
int isEmpty(Queue *h);
int inqueue(Queue *h, list_head *p);
list_head* outqueue(Queue *h);
#endif // QUEUE_H_INCLUDED
/*****代码*****/
#include <stdio.h>
#include <stdlib.h>
#include "squeue.h"
typedef struct mydata{
int id;
list_head memb;
double score;
}My;
void init(Queue *h){
h->prev = NULL;
h->rear = h->prev;
}
int isEmpty(Queue *h){
return h->prev == NULL;
}
int inqueue(Queue *h, list_head *p){
if(h!=NULL){
if(h->prev==NULL) h->prev = h->rear = p;
else{
h->rear->next = p;
h->rear = p;
}
return 1;
}
return 0;
}
list_head* outqueue(Queue *h){
list_head *p = NULL;
if(h!=NULL){
if(!isEmpty(h)){
p = h->prev;
if(p == h->rear) h->rear = h->prev = NULL; //如果队列里只有一个节点
else h->prev = p->next;
}
}
return p;
}
int main(){
int i;
Queue sq;
list_head *p = NULL;
My data1, data2, data3;
My *q = NULL;
init(&sq);
data1.id = 1;
data2.id = 2;
data3.id = 3;
if(inqueue(&sq,&data1.memb)) printf("succeed to inqueue\n"); //ruzhan
if(inqueue(&sq,&data2.memb)) printf("succeed to inqueue\n");
if(inqueue(&sq,&data3.memb)) printf("succeed to inqueue\n");
for(i=0;i<3;i++){
p = outqueue(&sq);
if(p==NULL) {
printf("error\n");
exit (0);
}
q = list_entry(My,p,memb);
printf("the id of data is %d\n",q->id);
}
return 0;
}