数据结构:循环队列

YUEXIABUG2022年4月7日
大约 2 分钟

实验目标:

提示

(1)初始化长度为MAXQSIZE的空队列

(2)新元素e入队列,成功返回true,失败返回false

(3)出队列,即删除队首元素,并用e返回出元素值,成功返回true,失败返回false

(4)读队首元素,用e返回队首元素,不出队 ,成功返回true,失败返回false

(5)遍历队列

(6)销毁队列


实验代码

#include <bits/stdc++.h>
using namespace std;

#define TRUE         1
#define FALSE        0
#define OK           1
#define ERROR        0
#define INFEASIBLE  -1
#define OVERFLOW    -2

#define MAXSIZE 100

typedef int Status;
typedef int QElemType;

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

Status InitQueue(SqQueue &Q)//初始化队列
{
    Q.base=(QElemType*)malloc(MAXSIZE *sizeof(QElemType));
    if(!Q.base)exit(OVERFLOW);
    Q.front=Q.rear=0;
    return OK;
}

Status EnQueue(SqQueue &Q,QElemType e)//入队列
{
    if((Q.rear+1) % MAXSIZE==Q.front) return ERROR;
    Q.base[Q.rear]=e;
    Q.rear=(Q.rear+1) % MAXSIZE;
    return OK;
}

Status DeQueue(SqQueue &Q,QElemType &e)//将队列首元素删除并返回其值
{
    if(Q.front==Q.rear) return ERROR;
    e=Q.base[Q.front];
    Q.front=(Q.front+1) % MAXSIZE;
    return OK;
}

Status GetHead(SqQueue &Q)//读出队首元素,不出队
{
    if(Q.front==Q.rear) return FALSE;
    cout<<Q.base[Q.front]<<endl;
    return OK;
}

Status Traverse(SqQueue &Q)//遍历队列
{
    if(Q.front==Q.rear) return FALSE;

    int i=Q.front;
    while(i!=Q.rear){
        cout<<Q.base[i]<<" ";
        i++;
        i=i%MAXSIZE;
    }
    return OK;
}

Status Destroy(SqQueue &Q)
{
    if(Q.front==Q.rear) return FALSE;

    if(Q.base) free(Q.base);
    Q.base=NULL;
    Q.front=Q.rear=0;
    return OK;
}

int main()
{
    SqQueue Q;
    int e;

    while(1){
		cout<<endl;
		cout<<"**1,初始化队列"<<endl;
		cout<<"**2,将元素e入列"<<endl;
	    cout<<"**3,出队列,用e返回出队列元素"<<endl;
	    cout<<"**4,返回列首元素"<<endl;
		cout<<"**5,遍历队列"<<endl;
		cout<<"**6,销毁队列"<<endl;
		cout<<"**0,退出系统"<<endl<<endl;

		int choice;
		cout<<"请输入要进行的操作:";
		cin>>choice;
		cout<<endl;

		switch(choice){
			case 1:InitQueue(Q);break;
			case 2:{
				int n;
				cout<<"请输入本次入队的元素个数:";
				cin>>n;

				cout<<endl<<"请输入要插入的元素:";
				for(int i=1;i<=n;i++){
					cin>>e;
					EnQueue(Q,e);
				}
				cout<<"入栈成功!"<<endl;
				break;
			}
			case 3:{
                DeQueue(Q,e);
				cout<<"出队成功!"<<endl;
				break;
			}
			case 4:GetHead(Q);break;
            case 5:Traverse(Q);break;
			case 6:Destroy(Q);break;
			case 0:exit(0);
		}
	}

    system("pause");
    return 0;
}
评论
Powered by Waline v2.6.1