现在的位置: 首页 > 综合 > 正文

队列的实现

2013年10月14日 ⁄ 综合 ⁄ 共 927字 ⁄ 字号 评论关闭

#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;
 
}

 

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

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

【上篇】
【下篇】

抱歉!评论已关闭.