循環隊列

      首先,熟悉了一下順序結構隊列的簡單操作:

#include <stdio.h>

#define MAX_SIZE 3

int Queue[MAX_SIZE];

int front = 0;				// 隊頭指針,指向隊頭元素
int rear = 0;				// 隊尾指針,指向隊尾元素的下一位置


int InQueue(int value)
{
	if (rear >= MAX_SIZE)
		return 0;
	
	Queue[rear] = value;
	rear++;

	return 1;
}


int OutQueue(int *value)
{
	if (rear == front)
		return 0;

	*value = Queue[front];
	front++;

	return 1;
}


int main()
{
	int temp;
	
	while(1){
		printf("1 存入:    2 讀取:");
		scanf("%d",&temp);
		fflush(stdin);
		
		if (1 == temp){
			printf("請輸入要存入的值:");
			scanf("%d",&temp);
			fflush(stdin);
			if (1 == InQueue(temp))
				printf("插入隊列成功!\n");
			else
				printf("隊列已滿!\n");
		}
		else if (2 == temp){
			if (1 == OutQueue(&temp))
				printf("讀取隊列的值爲 %d \n",temp);
			else
				printf("隊列爲空!\n");
		}
	}
	return 0;
}

      

      然後重點是應用比較多的循環隊列:

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

#define MAXQSIZE 3

typedef int QElemType;

typedef struct {
	QElemType *base;
	int front;
	int rear;
}SqQueue;


SqQueue *InitQueue()
{
	SqQueue *Q = (SqQueue *)malloc(sizeof(SqQueue));
	if (NULL == Q)
		exit(0);

	Q->base = (QElemType *)malloc(sizeof(QElemType));
	if (NULL == Q->base)
		exit(0);

	Q->front = Q->rear = 0;

	return Q;
}


int QueueLength(SqQueue *Q)
{
	return (Q->rear - Q->front + MAXQSIZE) % MAXQSIZE;
}


int InQueue(SqQueue *Q, QElemType e)
{
	if ((Q->rear + 1) % MAXQSIZE == Q->front)						// 隊列滿
		return 0;

	Q->base[Q->rear] = e;
	Q->rear = (Q->rear + 1) % MAXQSIZE;

	printf("rear = %d\n",Q->rear);
	return 1;
}


int OutQueue(SqQueue *Q, QElemType *e)
{
	if (Q->front == Q->rear)										// 隊列空
		return 0;

	*e = Q->base[Q->front];
	Q->front = (Q->front + 1) % MAXQSIZE;
	return 1;
}


int main()
{
	int temp, len;
	SqQueue *Q = InitQueue();
	
	while(1){
		printf("1 存入:    2 讀取:");
		scanf("%d",&temp);
		fflush(stdin);
		
		if (1 == temp){
			printf("請輸入要存入的值:");
			scanf("%d",&temp);
			fflush(stdin);
			if (1 == InQueue(Q,temp))
				printf("插入隊列成功!\n");
			else
				printf("隊列已滿!\n");
		}
		else if (2 == temp){
			if (1 == OutQueue(Q,&temp))
				printf("讀取隊列的值爲 %d \n",temp);
			else
				printf("隊列爲空!\n");
		}
		len = QueueLength(Q);
		printf("len = %d\n",len);
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章