链队列出队
时间: 2023-07-09 21:17:51 浏览: 45
链队列出队的具体操作如下:
1. 如果队列为空,直接返回空队列。
2. 如果队列不为空,保存队头节点的值,将队头指针指向下一个节点,释放原来队头节点的空间。
3. 如果队头指针为空,将队尾指针也置为空。
4. 返回保存的队头节点的值。
具体的代码实现如下:
```c++
// 定义队列节点结构体
struct Node {
int data;
Node *next;
Node(int val) : data(val), next(nullptr) {}
};
class Queue {
private:
Node *head; // 队头指针
Node *tail; // 队尾指针
public:
Queue() {
head = nullptr;
tail = nullptr;
}
// 出队操作
int dequeue() {
if (head == nullptr) {
cout << "队列为空!" << endl;
return -1;
}
int res = head->data;
Node *temp = head;
head = head->next;
delete temp;
if (head == nullptr) tail = nullptr;
return res;
}
};
```
注意:在出队操作中,需要注意队列为空的判断。另外,如果队列中只有一个节点,出队后需要将队尾指针也置为空。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)