queue.h
#ifndef __QUEUE_H__
#define __QUEUE_H__
typedef struct Queue_node
{
void *data;
struct Queue_node* next;
}Queue_node;
typedef struct Queue
{
struct Queue_node * head;
struct Queue_node *tail;
}Queue;
int queue_init(struct Queue* self);
int queue_empty(struct Queue* self);
int queue_put(struct Queue* self, void* data);
void* queue_get(struct Queue* self);
#endif
queue.c
#include "queue.h"
#include <stdlib.h>
#include <assert.h>
int queue_init(struct Queue* self)
{
if(self == NULL)
return -1;
else
{
self->head = NULL;
self->tail = NULL;
}
return 0;
}
int queue_empty(struct Queue* self)
{
return self->head == NULL;
}
int queue_put(struct Queue* self, void* data)
{
assert(self != NULL && data != NULL);
struct Queue_node *newnode = (struct Queue_node*)malloc(sizeof(Queue_node));
if(newnode == NULL)
return -1;
else
{
newnode->data = data;
newnode->next = NULL;
if(self->head == NULL)
{
self->head = newnode;
self->tail = newnode;
}
else
{
self->tail->next = newnode;
self->tail = newnode;
}
return 0;
}
}
void* queue_get(struct Queue* self)
{
void* data = NULL;
if(queue_empty(self) == 1)
return NULL;
else
{
data = self->head->data;
struct Queue_node* next = self->head->next;
free(self->head);
self->head=next;
return data;
}
}
queue_test.c
#include "queue.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int test_queue()
{
struct Queue queue;
int ret = queue_init(&queue);
if(ret < 0)
{
fprintf(stderr,"queue init failed\n");
return -1;
}
int data_array[10] = {0};
int i = 0;
srand(time(NULL));
while(i<10)
{
data_array[i] = rand()%100;
fprintf(stdout,"%d\t",data_array[i]);
ret = queue_put(&queue,&data_array[i]);
if(ret < 0)
{
fprintf(stderr,"put failed\n");
return -2;
}
i++;
}
fprintf(stdout,"\n");
int *p;
while(queue_empty(&queue)==0)
{
p =(int*) queue_get(&queue);
fprintf(stdout,"%d\t" ,*p);
}
fprintf(stdout,"\n");
return 0;
}
int main()
{
test_queue();
return 0;
}