带头结点的链队列的基本操作
时间: 2023-10-17 17:05:40 浏览: 187
带头结点的链队列是一种使用链表实现的队列结构,每个节点包含一个数据元素和一个指向下一个节点的指针。头结点不存储数据,只用于方便操作。
基本操作包括:
1. 初始化队列:创建一个头结点,并将队头指针和队尾指针指向头结点。
2. 判断队列是否为空:判断队头指针和队尾指针是否相等,如果相等则队列为空。
3. 入队操作:创建一个新节点,并将数据元素存入节点中,将队尾指针指向新节点。
4. 出队操作:将队头指针指向头结点的下一个节点,返回队头节点的数据元素。
5. 取队头元素:返回队头节点的数据元素,但不改变队列状态。
以下是带头结点的链队列的基本操作的代码实现:
```c++
#include <iostream>
using namespace std;
// 定义链队列结点结构体
struct Node {
int data;
Node *next;
};
// 定义带头结点的链队列结构体
struct Queue {
Node *front; // 队头指针
Node *rear; // 队尾指针
};
// 初始化队列
void initQueue(Queue &q) {
q.front = q.rear = new Node;
q.front->next = nullptr;
}
// 判断队列是否为空
bool isEmpty(Queue q) {
return q.front == q.rear;
}
// 入队操作
void enQueue(Queue &q, int x) {
Node *newNode = new Node;
newNode->data = x;
newNode->next = nullptr;
q.rear->next = newNode;
q.rear = newNode;
}
// 出队操作
int deQueue(Queue &q) {
if (isEmpty(q)) {
cout << "Queue is empty!" << endl;
return -1;
}
Node *p = q.front->next;
int x = p->data;
q.front->next = p->next;
if (q.rear == p) {
q.rear = q.front;
}
delete p;
return x;
}
// 取队头元素
int getFront(Queue q) {
if (isEmpty(q)) {
cout << "Queue is empty!" << endl;
return -1;
}
return q.front->next->data;
}
int main() {
Queue q;
initQueue(q);
cout << "Is queue empty? " << isEmpty(q) << endl;
enQueue(q, 1);
enQueue(q, 2);
enQueue(q, 3);
cout << "Front element: " << getFront(q) << endl;
cout << "Dequeue element: " << deQueue(q) << endl;
cout << "Front element: " << getFront(q) << endl;
return 0;
}
```
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)