编写两个函数,实现动态链表的建立和输出,主函数调用。用C++
时间: 2024-03-22 22:42:05 浏览: 33
好的,下面是实现动态链表建立和输出的两个函数:
```cpp
#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 = new ListNode(0), *p = head;
cout << "请输入链表各个节点的值: ";
for(int i = 0; i < n; i++) {
int val;
cin >> val;
ListNode *node = new ListNode(val);
p->next = node;
p = node;
}
return head->next;
}
//输出链表函数
void printList(ListNode *head) {
cout << "链表的值为: ";
while(head) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
//主函数
int main() {
ListNode *head = createList();
printList(head);
return 0;
}
```
主函数中先调用 createList() 函数建立链表,然后再调用 printList() 函数输出链表。在 createList() 函数中,首先输入链表节点的个数 n,然后输入每个节点的值,用 new 操作符动态创建一个新的节点,并将其插入到链表中。最后返回链表的头节点。在 printList() 函数中,遍历链表并输出节点的值。