帮我写一个链表的主函数
时间: 2023-07-25 17:17:57 浏览: 41
好的,以下是一个简单的链表主函数示例:
```c++
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* createList(int arr[], int n) {
if (n == 0) {
return NULL;
}
ListNode *head = new ListNode(arr[0]);
ListNode *cur = head;
for (int i = 1; i < n; i++) {
cur->next = new ListNode(arr[i]);
cur = cur->next;
}
return head;
}
void printList(ListNode *head) {
ListNode *cur = head;
while (cur != NULL) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(int);
ListNode *head = createList(arr, n);
printList(head);
return 0;
}
```
该函数实现了创建链表、打印链表的功能。可以根据需要进行修改和扩展。