(1)定义函数:建立一个具有n个结点的单向链表l,要求返回表头指针;\n(2)定义函数:统计结点个数,要求以表头指针作为调用函数,返回结点个数;\n(3)定义函数:在链表l的第i个结点前插入一个结点,要求
时间: 2023-04-19 16:04:21 浏览: 49
以表头指针作为参数,返回修改后的表头指针;
(1) 定义函数如下:
```c++
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* createList(int n) {
ListNode* head = nullptr;
ListNode* tail = nullptr;
for (int i = 1; i <= n; ++i) {
ListNode* node = new ListNode(i);
if (head == nullptr) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
```
(2) 定义函数如下:
```c++
int countNodes(ListNode* head) {
int count = ;
ListNode* p = head;
while (p != nullptr) {
++count;
p = p->next;
}
return count;
}
```
(3) 定义函数如下:
```c++
ListNode* insertNode(ListNode* head, int i, int val) {
if (i == 1) {
ListNode* node = new ListNode(val);
node->next = head;
return node;
}
ListNode* p = head;
for (int j = 1; j < i - 1 && p != nullptr; ++j) {
p = p->next;
}
if (p == nullptr) {
return head;
}
ListNode* node = new ListNode(val);
node->next = p->next;
p->next = node;
return head;
}
```