本题要求实现一个函数,建立一个链表,返回头指针(即头节点地址)
时间: 2023-12-14 15:37:52 浏览: 104
好的,理解了你的问题。以下是实现链表建立并返回头指针的函数示例:
```c++
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* createLinkedList(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;
}
int main() {
int arr[] = {1, 3, 5, 7, 9};
int n = sizeof(arr) / sizeof(int);
ListNode* head = createLinkedList(arr, n);
while (head != NULL) {
cout << head->val << "->";
head = head->next;
}
cout << "NULL" << endl;
return 0;
}
```
以上代码实现了一个简单的链表建立方法,并返回头指针的功能。你可以根据需要调整代码来适应你的项目。注意不要泄露任何信息。