本节介绍队列的定义及基本操作。
1)队列定义:
typedef struct __queue queue;
typedef struct __node node;
struct __queue
{
struct __node *front;
struct __node *rear;
int size;
};
struct __node
{
struct __node *pre;
struct __node *next;
void *data;
};
2)基本操作:
queue *create(void *data)
{
queue *q = NULL;
node *p = NULL;
q = (queue *)malloc(sizeof(struct __queue));
if (q == NULL)
{
perror("create queue node failed!\n");
return NULL;
}
q->front = NULL;
q->rear = NULL;
q->size = 0;
return q;
}
int en_queue(queue *q, void *data)
{
node *p;
if (q == NULL)
{
perror("invalid queue!\n");
return -1;
}
if (q->size > MAX_NODE)
{
perror("beyond max queue size!\n");
return -1;
}
p = (node *)malloc(sizeof(struct __node));
if (p == NULL)
{
perror("alloc new node failed!\n");
return -1;
}
p->data = malloc(sizeof(int));
*(int *)(p->data) = *(int *)data;
if (q->rear == NULL && q->front == NULL)
{
//add first node here;
q->front = p;
q->front->pre = NULL;
q->front->next = NULL;
q->rear = p;
q->rear->pre = NULL;
q->rear->next = NULL;
}
else
{
q->rear->next = p;
p->pre = q->rear;
p->next = NULL;
q->rear = p;
}
(q->size) ++;
return 0;
}
int de_queue(queue *q, void *data)
{
node *p = NULL;
if (q == NULL || q->size <= 0)
{
perror("invalid queue!\n");
return -1;
}
p = q->front;
*(int *)data = *(int *)(p->data);
if (p->next != NULL)
{
q->front = p->next;
q->front->pre = NULL;
}
(q->size) --;
free(p->data);
free(p);
return 0;
}
int destory_queue(queue *q)
{
node *p = NULL;
if (q == NULL)
return 0;
for (p = q->front; p != NULL; p = p->next)
{
free(p->data);
free(p);
}
free(q);
return 0;
}
3)打印所有元素:
int dump_queue(queue *q)
{
node *p = NULL;
int count = 0;
if (q == NULL)
{
perror("invalid queue!\n");
return -1;
}
for(p = q->front; p != NULL; p = p->next, count ++)
{
if (count != 0 && count % LINE_NUM == 0)
printf("\n");
printf("%d\t", *(int *)(p->data));
}
printf("\n");
return 0;
}
下一节将介绍测试代码及说明。