c 语言 单链表实现队列

最近复习数据结构,手撸代码,能运行

#include 
#include 
/*by xuyongqi*/

/*单链表实现队列*/

typedef struct node {
	void* data;
	struct node *next;
}node;

typedef struct queue {
	node *head;
	node *tail;
	int size;
}queue;
 
 /*初始化*/
void* init()
{
	queue* qe = (queue*)malloc(sizeof(queue));
	if(qe == NULL) return NULL;
	qe->head = NULL;
	qe->tail = NULL;
	qe->size = 0;
	return qe;
}

 /*销毁栈*/
void destory(void *qe)
{
	if(qe == NULL) return;
	queue *p =(queue*)qe;
	node *del = p->head;
	node *temp = NULL;
	while (del != NULL)
	{
	   temp = del->next;
	   free(del);
	   del = temp;
	}
	free(p);
	p = NULL;
}

 /*入队*/
void push(void *qe, void *data)
{
	if(qe ==NULL || data ==NULL) return;
	queue *p =(queue*)qe;
	node *new_node = (node*)malloc(sizeof(node));
	new_node->next = NULL;
	new_node->data = data;
	if(p->head == NULL)
	{
	    p->head = new_node;
	    p->tail = new_node;
	}else {
	    p->tail->next = new_node;
	    p->tail = new_node;
	}
	p->size++;
}

 /*出队*/
void pop(void *qe)
{
	if (qe== NULL) return;
	queue *p =(queue*)qe;
	if (p->size == 0) return;

	node *del = p->head;
	p->head = del->next;
	free(del);
	del = NULL;
	p->size--;
}

 /*返回队列顶元素*/
void* top(void *qe)
{
	if (qe== NULL) return NULL;
	queue *p =(queue*)qe;
	if (p->size == 0) return NULL;
	return p->head->data;
}

/*队列是否为空*/
int empty(void *qe)
{
	if (qe== NULL) return 0;
	queue *p =(queue*)qe;
	return p->size == 0;
}

/*队列中元素个数*/
int size(void *qe)
{
	if (qe== NULL) return -1;
	queue *p =(queue*)qe;
	return p->size;
}

int main()
{
	int d1 = 1;
	int d2 = 2;
	int d3 = 3;
	int d4 = 4;
	int d5 = 5;
	queue *q= init();

	push(q, &d1);
	push(q, &d2);
	push(q, &d3);
	push(q, &d4);
	push(q, &d5);

	while(!empty(q))
	{
	    int *i = (int*)top(q);
	    printf("top %d \n", *i);
	    pop(q);
	}
	destory(q);
}

你可能感兴趣的:(c语言,数据结构)