写队列的链队列的初始化,入队,出队,取队头,队列长度;循环队列的初始化,入队,出队,取队头,队列长度;
时间: 2023-09-30 20:09:58 浏览: 41
链队列的初始化、入队、出队、取队头、队列长度的实现代码如下:
```c++
#include <iostream>
using namespace std;
// 链队列结点
struct QueueNode {
int data;
QueueNode* next;
};
// 链队列
class LinkQueue {
public:
LinkQueue() {
front = rear = new QueueNode;
front->next = nullptr;
}
~LinkQueue() {
while (front != rear) {
QueueNode* p = front;
front = front->next;
delete p;
}
delete front;
}
void EnQueue(int x) {
QueueNode* p = new QueueNode;
p->data = x;
p->next = nullptr;
rear->next = p;
rear = p;
}
int DeQueue() {
if (front == rear) {
cout << "队列为空,无法出队" << endl;
return -1;
}
QueueNode* p = front->next;
int x = p->data;
front->next = p->next;
if (rear == p) {
rear = front;
}
delete p;
return x;
}
int GetFront() {
if (front == rear) {
cout << "队列为空,无法取队头" << endl;
return -1;
}
QueueNode* p = front->next;
return p->data;
}
int GetLength() {
int length = 0;
QueueNode* p = front->next;
while (p != nullptr) {
length++;
p = p->next;
}
return length;
}
private:
QueueNode* front; // 队头指针
QueueNode* rear; // 队尾指针
};
// 循环队列
class CircleQueue {
public:
CircleQueue(int n) {
data = new int[n];
front = rear = 0;
capacity = n;
}
~CircleQueue() {
delete[] data;
}
void EnQueue(int x) {
if ((rear + 1) % capacity == front) {
cout << "队列已满,无法入队" << endl;
return;
}
data[rear] = x;
rear = (rear + 1) % capacity;
}
int DeQueue() {
if (front == rear) {
cout << "队列为空,无法出队" << endl;
return -1;
}
int x = data[front];
front = (front + 1) % capacity;
return x;
}
int GetFront() {
if (front == rear) {
cout << "队列为空,无法取队头" << endl;
return -1;
}
return data[front];
}
int GetLength() {
return (rear - front + capacity) % capacity;
}
private:
int* data; // 存储队列元素的数组
int front; // 队头指针
int rear; // 队尾指针
int capacity; // 队列容量
};
```
以上代码实现了链队列和循环队列的各种操作,可以根据需要进行调用。
阅读全文