数据结构之队列的C语言实现

参考书籍:严蔚敏《数据结构》

#include <stdio.h>
#include <stdlib.h> 

typedef struct QNode{
	char data;
	struct QNode *next;
}QNode,*QueuePtr;

typedef struct{
	QueuePtr front;
	QueuePtr rear;
}LinkQueue;

bool initQueue(LinkQueue* Q)
{
	Q->front = Q->rear = (QueuePtr)malloc(sizeof(QNode));
	if(!Q->front)return 0;
	Q->front->next = NULL;
	return 1;
}

bool destroyQueue(LinkQueue* Q)
{
	while(Q->front)
	{
		Q->rear = Q->front->next;
		free(Q->front);
		Q->front = Q->rear;
	}
	return 1;
}

bool enQueue(LinkQueue* Q,char c)
{
	QNode* p = (QNode*)malloc(sizeof(QNode));
	if(!p) return 0;
	p->data = c;
	p->next = NULL;
	Q->rear->next = p;
	Q->rear = p;
	return 1;
}

bool deQueue(LinkQueue* Q,char* c)
{
	QueuePtr p; 
	if(Q->front == Q->rear)return 0;
	p = Q->front->next;
	*c = p->data;
	Q->front->next = p->next;
	if(Q->rear == p) Q->rear = Q->front; 
	free(p);
	return 1;
}

void display(LinkQueue Q)
{
	if(Q.rear == Q.front){printf("empty queue!");return;}
	QueuePtr p = Q.front->next;
	do
	{
		printf("%c  ",p->data);
		p = p->next;	
	}while(p != NULL);
	printf("\ndisplay over\n");
}

int main()
{
	LinkQueue Queue;
	char c;
	initQueue(&Queue);
	enQueue(&Queue,'c');
	enQueue(&Queue,'h');
	enQueue(&Queue,'e');
	enQueue(&Queue,'n');
	enQueue(&Queue,'x');
	display(Queue);
	deQueue(&Queue,&c);
	display(Queue);
	destroyQueue(&Queue);
	display(Queue);
	return 1;
}

运行结果:

posted @ 2019-08-18 12:07  昨夜昙花  阅读(7)  评论(0)    收藏  举报