泛型 队列

---------- MAIN.C
#include 
#include 
#include 
#include 
#include 
#include 
#include "queue.h" 
typedef struct {
	int a, b;
} coord;
void print(void *data)
{
	coord *cc = data;	
	printf("(%d, %d)->", cc->a, cc->b);	
	fflush(stdout);
}

coord *coord_make(int x, int y)
{
	coord *c = malloc(sizeof(coord));	
	c->a = x, c->b = y;
	return c;
}
void coord_free(void *data)
{
	free(data);
}
int main(int argc, char *argv[])
{
	Queue snake;
	queue_init(&snake);	
	coord *c[5];
	int i;
	for(i = 0; i < 5; i++)
		c[i] = coord_make(i,rand()%10);

	queue_en(&snake, c[0]);
	queue_en(&snake, c[1]);
	queue_en(&snake, c[2]);
	queue_en(&snake, c[3]);
	queue_en(&snake, c[4]);
	queue_print(&snake, print);
	puts("");
	queue_de(&snake);
	queue_en(&snake, c[3]);
	queue_print(&snake, print);
	puts("");

	queue_destroy(&snake, coord_free);
	queue_print(&snake, print);
	return 0;
}

---------- QUEUE.C
#include "queue.h"

void queue_init(Queue *q)
{
	q->head = NULL;
	q->tail = NULL;
	q->size = 0;
}
void queue_destroy(Queue *q, void(*dump)(void *))
{
	void *data;
	while(!queue_isempty(q))
	{
		data = queue_de(q);		
		dump(data);
	}


}
bool queue_isempty(Queue *q)
{
	return q->head == NULL;
}
static node make_node(void *data)
{
	node n = malloc(sizeof(node));
	n->data = data;
	n->next = NULL;
	return n;
}
static void free_node(node p)
{
	free(p);
}
void queue_en(Queue *q, void *data)
{
	node n = make_node(data);
	if(queue_isempty(q))
	{
		q->head = n;
		q->tail = n;
		q->size ++;
	}
	else
	{
		q->tail->next = n;
		q->tail = n;
	}
}
void *queue_de(Queue *q )
{
	if(queue_isempty(q))
	{
		return NULL;	
	}
	else
	{
		void *data = q->head->data;
		node del = q->head;
		q->head = del->next;
		free_node(del);
		return data;
	}
}
void queue_print(Queue *q, void (*print)(void *))
{
	if(queue_isempty(q))	
	{
		printf("Queue is empty!\n");
	}
	else
	{
		node save;
		for(save = q->head; save; save = save->next)
			print(save->data);
	}
}

---------- QUEUE.H
#ifndef _queue_h_
#define _queue_h_
#include 
#include 
#include 
typedef struct node_t *node;

struct node_t{
	struct node_t *next;
	void *data;
};

typedef struct {
	node head;
	node tail;
	ssize_t size;
} Queue;
void queue_init(Queue *q);
void queue_dump(Queue *q, void(*dump)(void *));
bool queue_isempty(Queue *q);
static node make_node(void *data);
static void free_node(node p);
void queue_en(Queue *q, void *data);
void *queue_de(Queue *q);
void queue_print(Queue *q, void (*print)(void *));

#endif // _queue_h_

  

转载于:https://www.cnblogs.com/mathzzz/archive/2012/08/29/2661270.html

你可能感兴趣的:(泛型 队列)