#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
//定义队列结构体
typedef struct _QUEUE_NODE
{
int* data;//存放数据指针
int head;//队列头
int tail;//队列尾
int length;//队列长度
} QUEUE_NODE;
//创建队列,并分配内存
QUEUE_NODE* allocate(int num)
{
if(0 == num)
{
return NULL;
}
QUEUE_NODE* node;
node = (QUEUE_NODE*)malloc(sizeof(QUEUE_NODE));
if (node == NULL)
return NULL;
memset(node, 0, sizeof(QUEUE_NODE));
node->data = (int *)malloc(sizeof(int)*num);
if (node->data == NULL)
{
free(node->data);
return NULL;
}
memset(node->data, 0, sizeof(int)*num);
node->length = num;
node->tail = node->head = 0;
return node;
}
//value进入队列, 从尾部进
int push(QUEUE_NODE *node, int value)
{
if (node == NULL)
return 0;
assert(node->data != NULL);
node->data[node->tail] = value;
printf("tail = %d, value = %d\n", node->tail, node->data[node->tail]);
node->tail = (node->tail+1) % node->length;
return 1;
}
//从头部出
int pop(QUEUE_NODE *node)
{
int value = 0;
if (node == NULL)
return 0;
assert(node->data != NULL);
value = node->data[node->head];
node->head = (node->head + 1) % node->length;
return value;
}
//测试用例
int main(int argc, char *argv[])
{
int value = 0;
int i=0;
QUEUE_NODE *node = allocate(5);
push(node, 1);
push(node, 2);
push(node, 3);
push(node, 4);
push(node, 5);
for(i=0; i<5; i++)
{
value = pop(node);
printf("pop is %d\n", value);
}
free(node->data);
free(node);
system("PAUSE");
return 0;
}