使用c++创建一个单链表其中的元素由键盘输入
时间: 2024-01-08 19:02:32 浏览: 33
当然!以下是一个示例代码,用于从键盘输入创建一个单链表:
```cpp
#include <iostream>
struct Node {
int data;
Node* next;
};
// 创建单链表
Node* createLinkedList() {
Node* head = nullptr; // 头节点指针
Node* tail = nullptr; // 尾节点指针
int value;
char choice;
do {
std::cout << "Enter a value: ";
std::cin >> value;
Node* newNode = new Node(); // 创建新节点
newNode->data = value; // 设置节点数据
newNode->next = nullptr; // 将next指针初始化为nullptr
if (head == nullptr) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
std::cout << "Do you want to continue? (y/n): ";
std::cin >> choice;
} while (choice == 'y' || choice == 'Y');
return head; // 返回头节点指针
}
// 打印单链表
void printLinkedList(Node* head) {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
int main() {
Node* head = createLinkedList();
std::cout << "Created linked list: ";
printLinkedList(head);
return 0;
}
```
在这段代码中,我们使用`createLinkedList`函数通过键盘输入逐个创建链表节点。在每次循环中,我们提示用户输入一个值,并将其存储在节点中。然后,根据链表是否为空,我们将新节点链接到链表的尾部。接着,我们询问用户是否要继续输入,如果是,则继续循环,否则退出循环。最后,我们通过调用`printLinkedList`函数打印链表的内容。
希望这对你有帮助!如果还有其他问题,请随时提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)