Chinaunix首页 | 论坛 | 博客
  • 博客访问: 605878
  • 博文数量: 99
  • 博客积分: 5128
  • 博客等级: 大校
  • 技术积分: 1538
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-27 19:40
文章分类

全部博文(99)

文章存档

2012年(3)

2011年(5)

2010年(4)

2009年(31)

2008年(56)

分类: C/C++

2009-07-07 21:49:41

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef int elem_t;

typedef struct _node NODE;
struct _node
{
    elem_t data;
    NODE *next;
};

typedef struct _queue queue_t;
struct _queue
{
    NODE *front;
    NODE *rear;
    int size;
};

int QueueIsEmpty(queue_t *q)
{
    return (q->size == 0);
}

queue_t *CreateQueue(void)
{
    queue_t *q;

    q = (queue_t *)malloc(sizeof(queue_t));
    if (q == NULL)
    {
        perror("create queue");
        exit(-1);
    }

    q->front = NULL;
    q->rear = NULL;
    q->size = 0;

    return q;
}

int DeleteQueue(queue_t *q)
{
    NODE *n,*s;

    s = n = q->front;
    while(n)
    {
        n = n->next;
        free(s);
        s = n;
    }

    free(q);

    return 0;
}
int InQueue(queue_t *q,elem_t d)
{
    NODE *n;

    n = (NODE *)malloc(sizeof(NODE));
    if (n == NULL)
    {
        perror("InQueue");
        exit(-1);
    }
    n->data = d;
    n->next = NULL;
    
    if (q->front == NULL)
    {
        q->front = q->rear = n;
    }else{
        q->rear->next=n;
        q->rear = n;
    }
    q->size++;

    return 0;
}

elem_t OutQueue(queue_t *q)
{
    elem_t retval;
    NODE *n;

    if (QueueIsEmpty(q))
    {
        printf("queue is empty");
        DeleteQueue(q);
        exit(1);
    }
    n = q->front;
    retval = n->data;
    q->front = n->next;
    q->size--;
    if (q->size == 0)
        q->front = q->rear = NULL;
    free(n);

    return retval;    
}



int main(int argc,char *argv[])
{
    queue_t *q;
    elem_t retval;

    q = CreateQueue();
    
    InQueue(q,10);
    InQueue(q,20);

    retval = OutQueue(q);
    printf("\nNode:%d",retval);

    retval = OutQueue(q);
    printf("\nNode:%d",retval);
    
    retval = OutQueue(q);

    DeleteQueue(q);

    return 0;
}


阅读(710) | 评论(0) | 转发(0) |
0

上一篇:顺序表实现队列

下一篇:递归实现全排列

给主人留下些什么吧!~~