赞
踩
(数据结构复习day5)
- #include <iostream>
- using namespace std;
-
- typedef int ElemType;
- const int QUEUE_INIT_SIZE = 100;
- const int QUEUEINCREMENT = 10;
- typedef struct {
- ElemType* data;
- int front;
- int rear;
- int queuesize;
- int incresize;
- }SqQueue;
-
- bool InitQueue(SqQueue& Q, int = QUEUE_INIT_SIZE, int = QUEUEINCREMENT);//初始化循环队列
- int QueueLength(SqQueue Q);//返回队列长度
- bool DeQueue(SqQueue& Q, ElemType& e);//将队首元素出队,用e返回
- bool EnQueue(SqQueue& Q, ElemType e);//将元素e放入循环队列
- bool GetHead(SqQueue Q, ElemType& e);//取队首元素,用e返回
- bool incrementQueuesize(SqQueue& Q);//当循环队列空间不足时,动态扩充空间
- void TraverseQueue(SqQueue Q);//遍历队列
- bool QueueEmpty(SqQueue Q);//判断队列是否为空
- bool ClearQueue(SqQueue& Q);//清空队列
-
- bool InitQueue(SqQueue& Q, int maxsize, int incresize) {
- Q.data = new ElemType[maxsize];
- if (!Q.data)return 0;
- Q.front = Q.rear = 0;
- Q.queuesize = maxsize;
- Q.incresize = incresize;
- return 1;
- }
- int QueueLength(SqQueue Q) {
- return (Q.rear - Q.front + Q.queuesize) % Q.queuesize;
- }
- bool DeQueue(SqQueue& Q, ElemType& e) {
- if (Q.front == Q.rear)
- return 0;
- e = Q.data[Q.front];
- Q.front = (Q.front + 1) % Q.queuesize;
- return 1;
- }
- bool EnQueue(SqQueue& Q, ElemType e) {
- if ((Q.rear + 1) % Q.queuesize == Q.front)
- if (!incrementQueuesize(Q))
- return 0;
- Q.data[Q.rear] = e;
- Q.rear = (Q.rear + 1) % Q.queuesize;
- return 1;
- }
- bool GetHead(SqQueue Q, ElemType& e) {
- if (Q.rear == Q.front)
- return 0;
- e = Q.data[Q.front];
- return 1;
- }
- bool incrementQueuesize(SqQueue& Q) {
- ElemType* newdata = new ElemType[Q.queuesize + Q.incresize];
- if (!newdata)return 0;
- for (int i = 0; i < Q.queuesize; i++)
- newdata[i] = Q.data[(Q.front + i) % Q.queuesize];
- delete[] Q.data;
- Q.data = newdata;
- Q.front = 0; Q.rear = Q.queuesize - 1;
- Q.queuesize += Q.incresize;
- return 1;
- }
- void TraverseQueue(SqQueue Q) {
- while (Q.front != Q.rear) {
- cout << Q.data[Q.front] << " ";
- Q.front = (Q.front + 1) % Q.queuesize;
- }
- cout << endl;
- }
- bool QueueEmpty(SqQueue Q) {
- if (Q.front == Q.rear)
- return 1;
- return 0;
- }
- bool ClearQueue(SqQueue& Q) {
- Q.front = Q.rear;
- return 1;
- }
-
-
- int main()
- {
- SqQueue Q;
- ElemType e;
- int i;
- if (InitQueue(Q, 8, 2))
- cout << "初始化循环队列成功(8个元素空间)" << endl;
- else {
- cout << "初始化循环队列失败" << endl;
- return 1;
- }
- cout << "请输入10个入队元素:" << endl;
- for (i = 0; i < 10; i++) {
- cin >> e;
- EnQueue(Q, e);
- }
- cout << "队列长度为" << QueueLength(Q);
- cout << "队列中元素为:";
- TraverseQueue(Q);
- cout << "出队5个元素" << endl;
- for (i = 0; i < 5; i++)
- DeQueue(Q, e);
- cout << "队列长度为" << QueueLength(Q) << endl;
- cout << "队列中元素为:";
- TraverseQueue(Q);
- cout << "请再输入6个入队元素:" << endl;
- for (i = 0; i < 6; i++) {
- cin >> e;
- EnQueue(Q, e);
- }
- cout << "队列长度为" << QueueLength(Q) << endl;
- cout << "队列中元素为:";
- TraverseQueue(Q);
- ClearQueue(Q);
- if (QueueEmpty(Q))
- cout << "队列已清空" << endl;
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。