队列的实现

来源:互联网 发布:ubuntu 修改时间 编辑:程序博客网 时间:2024/05/21 13:29
#include <stdio.h>#include <stdlib.h> struct node;struct node{    int num;    struct node *next;};//队列节点类型 // 队列变量struct fifo {    struct node *head,*tail;}; void init(struct fifo *p){    p->head = NULL;    p->tail = NULL;} int is_empty(struct fifo *p){    if( p->head == NULL )        return 1;    else        return 0;}void push(struct fifo *p, int i){    struct node *q;    q = (struct node *)malloc( sizeof(struct node) );    if( NULL == q )    {        printf("malloc error !!! \n");        return ;    }    q->num = i;    q->next = NULL;    if( is_empty(p) )    {        p->head = q;        p->tail = q;    }    else    {        p->tail->next = q;        p->tail = q;    }}int  pop(struct fifo *p, int *ret){    struct node *q;    if( is_empty(p) )    {        printf("fifo is empty !!! \n");        return 0;    }     *ret = p->head->num ;    q = p->head->next ;    free( p->head );    p->head = q;    return 1;} int main(){    int out, i, ret;    struct fifo q;    struct node *m;    init( &q );     pop(&q, &out);    for( i=0; i<10; i++ )        push(&q, i);    m = q.head;   // 先遍历一遍             while( m )    {        printf("%d  ", m->num);        m = m->next;    }    printf("\n");    for( i=0; i<12; i++ )    {        ret = pop(&q, &out);        if( ret )        {            printf("out==%d \n", out);        }    }    return 0; }

 


用链表实现了队列的一些操作,在链表尾部进入队列,在链表的头部出队列。

    希望大家多多指正,共同进步 !!!

原创粉丝点击