本期关注点当然是我们的队列,队列是先进先出的。
1.从队头出队,队尾入队。
2.判断队列为空的条件:Q.rear==Q.front
3.判断队列为满的条件:(Q.rear+1)%MaxSize==Q.front
4.求取长度:q.rear-q.front
本次实训关注点在于循环队列,将普通的队列尾与头相连操作代码如下:
#includeusing namespace std; #define MAXSIZE 100 typedef struct { char *elem; //顺序栈动态分配空间 int front; //顺序队列先进先出,front做头指针(做删除),rear做尾指针(做插入) int rear; }SqQueue; void InitSqQueue(SqQueue &q) { q.elem = new char[MAXSIZE]; //1.分配空间 if (!q.elem) cout << "分配空间失败!"; //判断分配空间是否成功 q.front = q.rear = 0; //2.队头队尾指针指向0,队列为空 cout << "初始化成功" << endl; } void InsertSqQueue(SqQueue& q) { //入队操作---入队rear的后面 cout << "入队操作,请输入入队个数:"; int n; cin >> n; cout << "再输入要入队的元素:"; for (int i = 0; i < n; i++){ char e; cin >> e; if ((q.rear + 1) % MAXSIZE == q.front) {//判断队列是否已满 cout << "队列满喽~"; } else { //如果未满,将元素直接放置顺序尾指针下表下 q.elem[q.rear] = e; q.rear = (q.rear + 1) % MAXSIZE; //循环队列的尾下表+1 } } } void DeQueue(SqQueue& q) { if (q.front==q.rear){ cout << "队列是空的,无法出队!"; } else{ cout << "请输入你要出队元素的个数:"; int n; cin >> n; cout << "出队元素为:"; for (int i = 0; i < n; i++){ char e; e = q.elem[q.front]; cout << e << " "; q.front = (q.front + 1) % MAXSIZE; //头指针+1 } cout << endl; } } void LengthSqQueue(SqQueue &q) { cout << "顺序栈的长度为:" << (q.rear - q.front + MAXSIZE) % MAXSIZE << endl;; //循环队列的情况下 //q.rear - q.front; 非循环队列的情况下 } void EmptySqQueue(SqQueue& q) { if (q.front==q.rear) { cout << "队列是空的!" << endl; } else { cout << "队列不为空!" << endl; } } void GetHead(SqQueue& q) { if (q.front!=q.rear) { //队列不为空时 取队列头元素 cout << "队头元素为:" << q.elem[q.front] << endl;//返回头元素指针下表 } else{ cout << "队列为空,无头元素!" << endl; } } int main() { SqQueue q; cout << "1.初始化:"; InitSqQueue(q); cout << "2."; InsertSqQueue(q); cout << "3."; LengthSqQueue(q); cout << "4."; GetHead(q); cout << "5."; DeQueue(q); cout << "6."; EmptySqQueue(q); }
代码运行截图:



