数据结构【一】:简单队列simple queue

简单的FIFO队列实现,非线程安全! 

 

1.queue.h : abstract data type queue

#ifndef CUR_QUEUE_H
#define CUR_QUEUE_H
#include<stdlib.h>
struct node{
    int value;
    struct node * next;
};


typedef struct queue{
     int max,cur;
     struct node * head, * tail;
}queue;


extern queue* empty_queue(int _max);
extern int queue_free(queue *q);
extern int is_empty(const queue *q);
extern int is_full(const queue *q);
extern int enqueue(struct node *item, queue *q);
extern struct node* dequeue(queue *q);

#endif

 

2.queue.c

#include "queue.h"

queue* empty_queue(int _max)
{
     queue *q = malloc(sizeof(queue));
     q->head  = q->tail = NULL;
     q->max   = _max;
     q->cur   = 0;
     return q;
}
 
int queue_free(queue *q)
{
    while(!is_empty(q))
        free(dequeue(q));
    free(q);
}

int is_empty(const queue *q)
{
    return q->cur == 0;
}

int is_full(const queue *q)
{
    return q->cur == q->max;
}

int enqueue(struct node *item, queue *q)
{
    if(is_full(q)) return -1;
    if(is_empty(q))
        q->head = q->tail = item;
    else
    {
        q->tail->next = item;
        q->tail = item;
    }
    q->cur++;
    return 0;
}

struct node* dequeue(queue *q)
{
    if(is_empty(q)) return NULL;
    struct node * temp = q->head;
    q->head = q->head->next;
    q->cur--;
    return temp;
}

 

 

3.main.c

#include<stdio.h>
#include<stdlib.h>
#include "queue.h"


void main()
{
 int i;
 queue *q = empty_queue(5);
 
 for(i=1; i<=10; i++){
     
     struct node * item = (struct node *)malloc(sizeof(struct node));
     item->value = i;
     item->next = NULL;

     printf("is_full : %d\n",is_full(q));
     if(is_full(q)) {
        printf("queue is full\n");
        printf("enqueue : %d\n",enqueue(item,q));
        break;
     }
     printf("enqueue : %d\n",enqueue(item,q));
 }

 while(!is_empty(q))
 {
     struct node * item = dequeue(q);
     if(item != NULL){
         printf("value : %d  ,current : %d\n", item->value,q->cur);
         free(item);
     }
 }
 queue_free(q);
}

 

测试结果:

 

 

posted @ 2013-12-30 16:46  liheping  Views(819)  Comments(0Edit  收藏  举报