用c++编写程序:实现顺序队列和链式队列。
时间: 2024-10-22 09:29:29 浏览: 21
链式队列的表示和实现源码
在C++中,我们可以使用数组来实现顺序队列(Array Queue),而链表来实现链式队列(Linked List Queue)。这里分别给出两种数据结构的基本实现:
**1. 顺序队列 (Array Queue)**
```cpp
#include <iostream>
#define MAX_SIZE 100 // 队列最大容量
class ArrayQueue {
private:
int front, rear; // 前端和后端指针
int items[MAX_SIZE]; // 数组存储元素
public:
ArrayQueue() : front(0), rear(0) {}
bool isEmpty() { return front == rear; }
bool isFull() { return rear == (front + MAX_SIZE - 1) % MAX_SIZE; }
void enqueue(int value) {
if (isFull()) {
std::cout << "Queue is full.\n";
return;
}
items[rear] = value;
rear = (rear + 1) % MAX_SIZE; // 使用环形缓冲区避免数组越界
}
int dequeue() {
if (isEmpty()) {
std::cout << "Queue is empty.\n";
return -1; // 返回错误值或抛异常
}
int value = items[front];
front = (front + 1) % MAX_SIZE;
return value;
}
};
int main() {
ArrayQueue q;
q.enqueue(1);
q.enqueue(2);
std::cout << "Dequeued: " << q.dequeue() << "\n"; // 输出: Dequeued: 1
return 0;
}
```
**2. 链式队列 (Linked List Queue)**
```cpp
#include <iostream>
using namespace std;
// 链表节点
struct Node {
int data;
Node* next;
};
class LinkedListQueue {
private:
Node* front, *rear;
public:
LinkedListQueue() : front(nullptr), rear(nullptr) {}
bool isEmpty() { return front == nullptr; }
void enqueue(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = rear;
if (isEmpty())
front = rear = newNode;
else
rear->next = newNode;
rear = newNode;
}
int dequeue() {
if (isEmpty()) {
cout << "Queue is empty.\n";
return -1; // 错误处理
}
int value = front->data;
Node* temp = front;
front = front->next;
delete temp;
if (front == nullptr)
rear = nullptr;
return value;
}
};
int main() {
LinkedListQueue q;
q.enqueue(1);
q.enqueue(2);
cout << "Dequeued: " << q.dequeue() << "\n"; // 输出: Dequeued: 1
return 0;
}
```
阅读全文