1、任务描述:编写函数,采用链式存储和顺序存储实现队列的初始化、入队、出队操作
2、亮点:
①对于顺序操作增添了函数IsFull(),用来判断队列有没有满,如果满了就重新分配空间
②由于存在分配在堆上的资源,实现了析构函数
3、运行情况:
4、源代码:
#include <iostream>
#define QueueElemType int
using namespace std;
class Queue {
private:
QueueElemType* Q;
int front = 0;
int rear = 0;
int length = 3;
public:
Queue() {
Q = new int[length];
}
void CheckFull() {
if (rear < length && rear - front + 1 < length)
return;
QueueElemType* p = new int[length * 2];
int i = front, j = 0;
while (i <= rear) {
p[j++] = Q[i++];
}
delete[]Q;
Q = p;
front = 0;
rear = j - 1;
length *= 2;
}
void InQueue(QueueElemType e) {
CheckFull();
Q[rear++] = e;
}
void OutQueue() {
if (rear == front) {
cout << "队列为空!" << endl;
return;
}
cout << Q[front++] << " ";
}
~Queue() {
delete[] Q;
}
};
class LinkedQueue {
private:
class QNode{
public:
QueueElemType date;
QNode* next;
};
QNode* front = NULL;
QNode* rear = NULL;
public:
void InQueue(QueueElemType e) {
if (NULL == front) {
rear = front = new QNode;
}
else {
rear->next = new QNode;
rear = rear->next;
}
rear->date = e;
rear->next = NULL;
}
void OutQueue() {
if (NULL == rear) {
cout << "队列为空!" << endl;
return;
}
cout << front->date << " ";
front = front->next;
}
~LinkedQueue() {
QNode* p = front;
while (NULL != p) {
front = front->next;
delete p;
p = front;
}
}
};
int main()
{
Queue Q;
for (int i = 0; i < 10; i++)
Q.InQueue(i);
for (int i = 0; i < 5; i++)
Q.OutQueue();
for (int i = 0; i < 5; i++)
Q.InQueue(i+10);
for (int i = 0; i < 10; i++)
Q.OutQueue();
cout << endl << endl;
LinkedQueue LQ;
for (int i = 0; i < 10; i++)
LQ.InQueue(i);
for (int i = 0; i < 5; i++)
LQ.OutQueue();
for (int i = 0; i < 5; i++)
LQ.InQueue(i + 10);
for (int i = 0; i < 10; i++)
LQ.OutQueue();
}