相关资料:
// 1. 过程抽象与封装实现队列
#include <iostream>
using namespace std;
const int MAX_QUEUE_SIZE = 100; // 队列最大容量
// 数组实现的队列结构体
struct Queue
{
int front; // 队首元素数组下标
int rear; // 队尾元素数组下标
int size; // 当前队列大小
int buffer[MAX_QUEUE_SIZE];
};
// 队列初始化
void init(Queue &q)
{
q.front = q.rear = 0;
q.size = 0;
}
// 入队操作
void push(Queue &q, int i)
{
if (q.size == MAX_QUEUE_SIZE)
{
cout << "Queue is overflow.\n";
exit(-1);
}
else
{
q.buffer[q.rear] = i;
q.rear = (q.rear + 1) % MAX_QUEUE_SIZE;
q.size += 1;
return;
}
}
// 出队操作
void pop(Queue &q, int &i)
{
if (q.size == 0)
{
cout << "Queue is empty.\n";
exit(-1);
}
else
{
i = q.buffer[q.front];
q.front = (q.front + 1) % MAX_QUEUE_SIZE;
q.size -= 1;
return;
}
}
// 获取队首/队尾元素
void get_queue(Queue &q)
{
if (q.front == q.rear)
{
cout << "Queue is empty.\n";
}
else
{
cout << "front element: " << q.buffer[q.front] << endl;
cout << "rear element: " << q.buffer[q.rear-1] << endl;
cout << "front index: " << q.front << endl;
cout << "rear index: " << q.rear << endl;
cout << "queue size: " << q.size << endl;
return;
}
}
int main()
{
Queue q;
int x;
init(q);
push(q, 2);
push(q, 3);
push(q, 4);
pop(q, x);
get_queue(q);
return 0;
}
// 2. 数据抽象与封装实现队列
// 2.1 数组实现
#include <iostream>
using namespace std;
const int MAX_QUEUE_SIZE = 100;
class Queue
{
public:
Queue();
void push(int i);
void pop(int &i);
void get_queue();
private:
int front; // 队首元素数组下标
int rear; // 队尾元素数组下标
int size; // 当前队列大小
int buffer[MAX_QUEUE_SIZE];
};
// 队列初始化
Queue::Queue()
{
front = rear = 0;
size = 0;
}
// 入队操作
void Queue::push(int i)
{
if (size == MAX_QUEUE_SIZE)
{
cout << "Queue is overflow.\n";
exit(-1);
}
else
{
buffer[rear] = i;
rear = (rear + 1) % MAX_QUEUE_SIZE;
size += 1;
return;
}
}
// 出队操作
void Queue::pop(int &i)
{
if (size == 0)
{
cout << "Queue is empty.\n";
exit(-1);
}
else
{
i = buffer[front];
front = (front + 1) % MAX_QUEUE_SIZE;
size -= 1;
return;
}
}
// 获取队首/队尾元素
void Queue::get_queue()
{
if (front == rear)
{
cout << "Queue is empty.\n";
}
else
{
cout << "front element: " << buffer[front] << endl;
cout << "rear element: " << buffer[rear-1] << endl;
cout << "front index: " << front << endl;
cout << "rear index: " << rear << endl;
cout << "queue size: " << size << endl;
return;
}
}
int main()
{
Queue q;
int x;
q.push(12);
q.push(15);
q.push(20);
q.pop(x);
q.get_queue();
return 0;
}
网友评论