编写一个链队列,任意输入一串字符然后将队列中的元素显示到屏幕上
时间: 2024-02-03 22:13:15 浏览: 36
以下是使用 C++ 语言编写的链队列实现,并且实现任意输入一串字符并将其添加到队列中,最后将队列中的元素显示到屏幕上。
```c++
#include <iostream>
using namespace std;
// 链队列结点
struct Node {
char data;
Node* next;
};
class LinkedQueue {
public:
LinkedQueue();
~LinkedQueue();
bool isEmpty();
void enqueue(char data);
char dequeue();
void display();
private:
Node* front; // 队头指针
Node* rear; // 队尾指针
};
LinkedQueue::LinkedQueue() {
front = rear = new Node;
front->next = NULL;
}
LinkedQueue::~LinkedQueue() {
while (front != rear) {
Node* p = front;
front = front->next;
delete p;
}
delete front;
}
bool LinkedQueue::isEmpty() {
return front == rear;
}
void LinkedQueue::enqueue(char data) {
Node* p = new Node;
p->data = data;
p->next = NULL;
rear->next = p;
rear = p;
}
char LinkedQueue::dequeue() {
if (isEmpty()) {
cout << "Queue is empty!" << endl;
exit(1);
}
Node* p = front->next;
char data = p->data;
front->next = p->next;
if (rear == p) {
rear = front;
}
delete p;
return data;
}
void LinkedQueue::display() {
Node* p = front->next;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main() {
LinkedQueue q;
string str;
cout << "Please input a string:";
getline(cin, str);
for (int i = 0; i < str.length(); i++) {
q.enqueue(str[i]);
}
cout << "Elements in the queue: ";
q.display();
return 0;
}
```
输出结果:
```
Please input a string:Hello, world!
Elements in the queue: H e l l o , w o r l d !
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)