c++编写两个函数,实现链表的建立和输出,主函数调用。
时间: 2024-02-11 15:05:19 浏览: 44
好的,下面是两个函数的实现,以及主函数的调用示例:
```c++
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 建立链表
ListNode* createList() {
int n;
cout << "请输入链表长度:";
cin >> n;
ListNode* head = NULL, * tail = NULL;
for (int i = 0; i < n; i++) {
int num;
cout << "请输入第" << i + 1 << "个节点的值:";
cin >> num;
ListNode* newNode = new ListNode(num);
if (head == NULL) {
head = tail = newNode;
}
else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// 输出链表
void printList(ListNode* head) {
ListNode* cur = head;
while (cur != NULL) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
int main() {
ListNode* head = createList();
printList(head);
return 0;
}
```
主函数中,我们先通过 `createList` 函数创建了一个链表,并返回链表的头结点指针,然后将该指针作为参数传递给 `printList` 函数,来输出整个链表。注意,这里的 `ListNode` 结构体是一个单向链表的节点结构体,包含一个整型成员变量 `val` 和一个指向下一个节点的指针成员变量 `next`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)