⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 5.4.c

📁 数据结构(c)循环队列存储结构的全部操作
💻 C
字号:
//循环队列的实现
//库函数和常量定义:
#include <malloc.h>
#include <stdio.h>
#include <iostream.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
//(1)循环队列存储结构定义:
#define MAXQSIZE 100 
typedef int Status;
typedef char QElemType;
typedef struct QNode{
	QElemType data;
	struct QNode *next;
}QNode,*QueuePtr;
typedef struct{
    QElemType *base;
	int front;
	int rear;
}SqQueue;
//(2)构造一个空的循环队列 
Status InitQueue (SqQueue *Q)
{//构造一个空队列Q
	Q->base=(QElemType *)malloc(MAXQSIZE*sizeof(QElemType));
	if (!Q->base) return ERROR;
	Q->front=Q->rear=0;
	return OK;
}

//(3)进队算法实现:
Status EnQueue(SqQueue *Q,QElemType e)
{	//插入元素e为Q的新的队尾元素
	if ((Q->rear+1)%MAXQSIZE==Q->front)
		//队列满
		return ERROR;
	Q->base[Q->rear]=e;
	Q->rear=(Q->rear+1)%MAXQSIZE;
	return OK;}

//(4)求队列的长度算法
int QueueLengh(SqQueue Q){
    //返回Q的元素个数,即队列的长度
	return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}

//(5)出队操作算法
Status DeQueue(SqQueue *Q,QElemType *e)
{
	//若队列不空,则删除Q的队头元素,用e返回其值,并返回OK;
	//否则返回ERROR;
	if (Q->front==Q->rear) return ERROR;
	*e=Q->base[Q->front];
	Q->front=(Q->front+1)%MAXQSIZE;
	return OK;
}

//(6)遍历队列算法
Status QueueTraverse(SqQueue Q)
{	int p;
	if (Q.front!=Q.rear)
	{
    p=Q.front;
	printf("\n队列中的内容为:");
	while(p!=Q.rear)
	{
	   printf("%c",Q.base[p] );
	   p=(p+1)%MAXQSIZE;
	}
	printf("\n");
	return OK;
	}
	else return ERROR;}

//(7)清空队列算法?
Status ClearQueue(SqQueue *Q){
//清空队列Q
if (!Q->base)  return (ERROR);
    Q->front=Q->rear;  //队列为空
	printf("队列已清空!");
	return OK;}

//(8)判队列为空算法
Status QueueEmpty(SqQueue Q)
{
	if (Q.front==Q.rear ) 
	{
		printf("队列为空!\n");
		return TRUE;
	}
	else return FALSE;
}

//(9)获得队列头结点
Status GetHead(SqQueue Q,QElemType *e)
{
	if (Q.front!=Q.rear ) {*e=Q.base[Q.front];return OK;}
	else
	{printf("sorry!Queue Empty!");return ERROR;}
}
void main()         
{
	SqQueue Q;QElemType e;
	InitQueue (&Q);
	EnQueue(&Q,'a');
	EnQueue(&Q,'b');
	EnQueue(&Q,'c');
	EnQueue(&Q,'d');
    QueueTraverse(Q);
	QueueEmpty(Q);
	QueueLengh(Q);
	GetHead(Q,&e);
	printf("头结点:%c\n",e);
	DeQueue(&Q,&e);
	printf("%c已出队\n",e);
	ClearQueue(&Q);
	QueueEmpty(Q);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -