数据结构队列链表实现

#include <stdio.h>
#include <malloc.h>

#define QLengh (sizeof(struct queue))

typedef struct queue
{
	int element;
	struct queue *next; 
}
*Queue;

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

void initQueue(LinkQueue *Q)
{
	Q->front=Q->rear=malloc(QLengh);	
	if(Q->rear==NULL)
	{
		printf("Out of space\n");	
	}
	else
	{
		Q->rear->next=NULL;
	}
} 

void insertQueue(LinkQueue *Q,int element)
{
	Queue NewQueue=malloc(QLengh);	
	if(NewQueue==NULL)
	{
		printf("Out of space\n");
	}	
	else
	{
		NewQueue->element=element;
		NewQueue->next=NULL; 
		Q->rear->next=NewQueue;
		Q->rear=NewQueue;
	}
}

int isEmpty(LinkQueue *Q)
{
	return (Q->front->next==NULL);
}

void outQueue(LinkQueue *Q)
{
	Queue Qtmp=NULL; 
	if(isEmpty(Q))
	{
		printf("Empty Queue\n");
	}
	else
	{
		Qtmp=Q->front;
		Q->front=Q->front->next;		
		free(Qtmp);
	}
}

void printQueue(LinkQueue *Q)
{
	Queue P=Q->front->next;
	while(P!=NULL)
	{
		printf("----------\n");
		printf("    %d    \n",P->element);
		printf("----------\n");
		P=P->next;
	}
} 

int main(void)
{
	LinkQueue Q;
	initQueue(&Q);
	printf("入队演示\n"); 
	insertQueue(&Q,1);
	insertQueue(&Q,2);
	insertQueue(&Q,3);
	insertQueue(&Q,4);
	insertQueue(&Q,5);
	printQueue(&Q);
	printf("出队演示\n"); 
	outQueue(&Q);
	outQueue(&Q);
	printQueue(&Q);
}

运行结果:

 

posted on 2017-07-05 21:06  HelloWorldTotti  阅读(166)  评论(0编辑  收藏  举报

导航