链队列 通用链表实现

链队列 通用链表实现

通过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;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值