请编写链队列的入队和出队算法。
时间: 2024-05-14 08:17:01 浏览: 7
好的,以下是链队列的入队和出队算法的示例代码:
入队代码:
```c++
void enqueue(Node*& rear, int data){
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
if(rear == NULL){
rear = newNode;
rear->next = rear;
}
else{
newNode->next = rear->next;
rear->next = newNode;
rear = newNode;
}
}
```
出队代码:
```c++
int dequeue(Node*& rear){
if(rear == NULL){
cerr<<"队列为空!"<<endl;
exit(1);
}
else if(rear == rear->next){
int data = rear->data;
delete rear;
rear = NULL;
return data;
}
else{
Node* front = rear->next;
int data = front->data;
rear->next = front->next;
delete front;
return data;
}
}
```
其中,Node为链队列的结构体,包含了数据data和指向下一个节点的指针next。rear为指向队尾节点的指针,初始值为NULL。在入队算法中,如果rear为NULL,则说明队列为空,新节点既是首节点也是尾节点;否则,将新节点插入到rear和rear->next之间,并将rear指向新节点。在出队算法中,若rear为NULL,则说明队列为空,否则分别处理队列只有一个节点和有多个节点的情况。如果只有一个节点,则直接删除此节点,并将rear指向NULL;否则,删除首节点,并将rear->next指向新的首节点。
相关推荐
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)