本文主要是介绍循环队列入队出队判队空队满,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
循环队列:
结构:
typedef struct
{ElemType *data; //数据域int front; //队头int rear; //队尾 下标代替指针
}SqQueue;
- 初始化队列
初始化队列让Q.front = Q.rear = 0 即可 - 判队空
判空 判断等式是否成立: Q.front == Q.rear - 判队满
判队满 因为循环队列会空出来一个位置
(Q.rear + 1) % MAXSIZE == Q,front
- 入队
让队尾指针后移,后移之后再输入元素 - 出队
代码:
#ifndef _SQQUEUE_H_
#define _SQQUEUE_H_#include <iostream>
#include <fstream>
using namespace std;#define OK 1
#define ERROR 0
#define MAXSIZE 5typedef int Status;
typedef int ElemType;typedef struct
{ElemType *data; //数据域int front; //队头int rear; //队尾 下标代替指针
}SqQueue;Status initSqQueue(SqQueue &Q)
{Q.data = (ElemType *)malloc(sizeof(ElemType) * MAXSIZE);if (!Q.data){cout << "空间不足";return ERROR;}Q.front = Q.rear = 0;
}bool isEmpty(SqQueue &Q)
{if (Q.front == Q.rear)return true;return false;
}bool isFull(SqQueue &Q)
{if ((Q.rear + 1) % MAXSIZE == Q.front)return true;return false;
}Status EnQueue(SqQueue &Q, ElemType e)
{if (isFull(Q)){cout << "队满,无法插入元素\n";return OVERFLOW;}Q.rear = (Q.rear + 1) % MAXSIZE;Q.data[Q.rear] = e;return OK;
}Status DeQueue(SqQueue &Q, ElemType &e)
{if (isEmpty(Q)){cout << "队空,无法删除元素\n";return ERROR;}Q.front = (Q.front + 1) % MAXSIZE;e = Q.data[Q.front];return OK;
}void Visit(SqQueue Q) //遍历循环队列
{int p = (Q.front + 1) % MAXSIZE;if (p <= Q.rear){for (p; p <= Q.rear; p++)cout << Q.data[p] <<" ";}else{for (p; p < MAXSIZE; p++)cout << Q.data[p] <<" ";p = 0;for (p; p <= Q.rear; p++)cout << Q.data[p] <<" ";}cout << endl;
}
#endif
这篇关于循环队列入队出队判队空队满的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!