隊列-數組實現

//Queue.h
#ifndef _QUEUE_H_
struct QueueRecord;
typedef struct QueueRecord *Queue;
#define ElementType int

struct QueueRecord
{
	int Capacity;
	int Front;
	int Rear;
	int Size;
	ElementType *Array;
};

Queue CreateQueue(int MaxElements);
int IsEmpty(Queue Q);
int IsFull(Queue Q);
void MakeEmpty(Queue Q);
int Succ_Rear(int Value,Queue Q);
void Enqueue(ElementType X, Queue Q);
ElementType Front(Queue Q);
ElementType FrontandDequeue(Queue Q);
void DisposeQueue(Queue Q);
void PrintQueue(Queue Q);


#endif
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//Queue.c 
#include<stdio.h>
#include "Queue.h"
#include<stdlib.h>

Queue CreateQueue(int MaxElements)
{
	Queue Q;
	Q=malloc(sizeof(struct QueueRecord));
	
	if(Q==NULL)
	{
		printf("Out of space!\n");
	}
	
	Q->Array=malloc(sizeof(ElementType)*MaxElements);
	Q->Capacity=MaxElements;
	
	if(Q->Array==NULL)
	{
		printf("Out of space!\n");
	}
	MakeEmpty(Q);
	
	return Q;
}

int IsEmpty(Queue Q)
{
	return Q->Size==0;
}

int IsFull(Queue Q)
{
	return Q->Size==Q->Capacity;
}

void MakeEmpty(Queue Q)
{
	Q->Size=0;
	Q->Front=1;
	Q->Rear=0;
}

int Succ_Rear(int Value,Queue Q)
{
	if((Value++)==Q->Capacity-1)
	{
		Value=0;
	}
	
	return Value;
}

void Enqueue(ElementType X, Queue Q)
{
	if(IsFull(Q))
	{
		printf("Out of space!\n");
	}
	else
	{
		Q->Size++;
		Q->Rear=Succ_Rear((Q->Rear),Q);
		printf("Rear的值 %d\n",Q->Rear);
		Q->Array[Q->Rear]=X;
	}
}

ElementType Front(Queue Q)
{
	if(!IsEmpty(Q))
	{
		return Q->Array[Q->Front];
	}
	
	printf("Empty queue!\n");
	
	return 0;
}

ElementType FrontandDequeue(Queue Q)
{
	ElementType temp=0;
	if(!IsEmpty(Q))
	{
		Q->Size--;
		temp=Q->Array[Q->Front];
		Q->Front--; 
		return temp;
	} 
	else
	{
		printf("Empty queue!\n");
		return 0;
	}
}

void DisposeQueue(Queue Q)
{
	if(IsEmpty(Q))
	{
		printf("Out of space!\n");          
	}
	else
	{
		Q->Size--;
		Q->Front++;
	}
} 

void PrintQueue(Queue Q)
{
	int j,n;
	j=Q->Front;
	n=0;
	while(n!=Q->Size)
	{
		if((j/(Q->Capacity-1))==1)
		{
			printf("%d",Q->Array[(j%(Q->Capacity))]);
			n++;
			j++;
		}
		else
		{
			printf("%d",Q->Array[j]);
			n++;
			j++;
		}
	}
	
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//main.c 
#include<stdio.h>
#include "Queue.h"


int main(void)
{
	Queue Q;
	Q=CreateQueue(10);
	
	int i;
	
	printf("請輸入整數加入隊列:\n");
	
	int m;
	scanf("%d",&m);
	
	while(m!=99)
	{
		Enqueue(m,Q);
		printf(" 隊列中: %d\n",Q->Array[Q->Rear]);
		printf("請輸入整數加入隊列:\n");
		scanf("%d",&m);
	}
	
	PrintQueue(Q);
	
	
	
	
	
	return 0;
}
相關文章
相關標籤/搜索