c++输入链表输出链表
时间: 2023-10-19 13:07:42 浏览: 45
你可以使用C++来输入链表和输出链表。以下是一个简单的示例代码:
```cpp
#include <iostream>
// 链表节点的定义
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
// 输入链表
ListNode* inputLinkedList() {
int n;
std::cout << "输入链表节点个数: ";
std::cin >> n;
ListNode* head = nullptr;
ListNode* curr = nullptr;
std::cout << "输入链表节点值: ";
for (int i = 0; i < n; i++) {
int val;
std::cin >> val;
ListNode* newNode = new ListNode(val);
if (head == nullptr) {
head = newNode;
curr = newNode;
} else {
curr->next = newNode;
curr = curr->next;
}
}
return head;
}
// 输出链表
void outputLinkedList(ListNode* head) {
std::cout << "链表节点值: ";
while (head != nullptr) {
std::cout << head->val << " ";
head = head->next;
}
std::cout << std::endl;
}
int main() {
ListNode* head = inputLinkedList();
outputLinkedList(head);
return 0;
}
```
在这个示例中,我们首先定义了一个名为 `ListNode` 的结构体,用于表示链表的节点。然后,我们编写了两个函数 `inputLinkedList` 和 `outputLinkedList` 分别用于输入和输出链表。
在 `inputLinkedList` 函数中,我们首先要求用户输入链表节点的个数。然后,我们使用一个循环来读取每个节点的值,并将其插入链表中。最后,函数返回链表的头节点。
在 `outputLinkedList` 函数中,我们遍历链表并输出每个节点的值。
在 `main` 函数中,我们首先调用 `inputLinkedList` 函数来输入链表,然后调用 `outputLinkedList` 函数来输出链表的节点值。
你可以根据自己的需要修改代码,并根据输入和输出格式进行相应的调整。希望对你有帮助!