现在的位置: 首页 > 综合 > 正文

循环队列

2013年03月11日 ⁄ 综合 ⁄ 共 1665字 ⁄ 字号 评论关闭

      首先,熟悉了一下顺序结构队列的简单操作:

#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;
}

抱歉!评论已关闭.