泛型 队列

---------- MAIN.C
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#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 <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值