红联Linux门户
Linux帮助

算法-数据结构-队列

发布时间:2005-09-09 17:46:58来源:红联作者:frog
/*********************************************************
Title : queue.c
Author : zhanglong
Time : 200508
**********************************************************/




#include
#include
#include




#define MEMASSERT(p,s) if(!p){fprintf(stderr,"Queue-No Memory: %s!\n",s);exit(0);}

#ifdef DEBUG_AC
int max_memory = 0;
#endif

/*------------------------------------------------*/
void *AC_MALLOC (int n)
{
void *p;
p = malloc (n);
#ifdef DEBUG_AC
if (p)
max_memory += n;
#endif
return p;
}

/*----------------------------------------------*/
void AC_FREE (void *p)
{
if (p)
free (p);
}

/*------Simple QUEUE NODE------*/
typedef struct _qnode
{
int data;
struct _qnode *next;
} QNODE;

/*-------Simple QUEUE Structure-------*/
typedef struct _queue
{
QNODE * head, *tail;
int count;
} QUEUE;





/*===============function declaration======================*/
void queue_init (QUEUE * s);
void queue_add (QUEUE * s, int data);
int queue_remove (QUEUE * s);
int queue_count (QUEUE * s);
void queue_free (QUEUE * s);




/*================function implementation===================*/
/*-------queue init-------*/
void queue_init (QUEUE * s)
{
s->head = s->tail = 0;
s->count = 0;
}


/*------------Add Tail Item to queue----------------*/
void queue_add (QUEUE * s, int data)
{
QNODE * q;

if (!s->head){
q = s->tail = s->head = (QNODE *) AC_MALLOC (sizeof (QNODE));
MEMASSERT (q, "queue_add");
q->data = data;
q->next = 0;
}
else{
q = (QNODE *) AC_MALLOC (sizeof (QNODE));
MEMASSERT (q, "queue_add");
q->data = data;
q->next = 0;
s->tail->next = q;
s->tail = q;
}

s->count++;
}


/*-------Remove Head Item from queue-------------*/
int queue_remove (QUEUE * s)
{
int data = 0;
QNODE * q;
if (s->head){
q = s->head;
data = q->data;
s->head = s->head->next;
s->count--;
if (!s->head){
s->tail = 0;
s->count = 0;
}
AC_FREE (q);
}
return data;
}


/*---------------queue count-----------------*/
int queue_count (QUEUE * s)
{
return s->count;
}


/*---------------queue free----------------*/
void queue_free (QUEUE * s)
{
while (queue_count (s)){
queue_remove (s);
}
}




/*=============main function=======*/
int main(int argc, char *argv[])
{
QUEUE * s;
s=(QUEUE *)AC_MALLOC(sizeof(QUEUE));
int i;

queue_init(s);

for(i=0;i<100;i+=3){
queue_add(s,i);
}
printf("queue count is %d\n",queue_count(s));

queue_remove(s);
printf("queue count is %d\n",queue_count(s));
queue_remove(s);
printf("queue count is %d\n",queue_count(s));
queue_remove(s);
printf("queue count is %d\n",queue_count(s));

printf("queue head is %d\n",s->head->data);
printf("queue tail is %d\n",s->tail->data);

queue_free(s);
printf("queue count is %d\n",queue_count(s));

}
文章评论

共有 2 条评论

  1. eoboot 于 2005-11-29 14:00:47发表:

    感谢分享

  2. ccs 于 2005-09-12 00:21:45发表:

    受教