递归向单链表中插入数据
时间: 2023-09-29 12:02:56 浏览: 61
递归向单链表中插入数据的思路如下:
1. 首先,需要先找到要插入数据的位置,也就是找到该节点的前一个节点。
2. 然后,将新节点插入到该位置。
3. 最后,将新节点的 next 指向原来该位置的节点。
4. 如果链表为空,则将新节点作为头节点。
以下是递归向单链表中插入数据的示例代码:
```
/**
* 向单链表中插入数据
* @param head 头节点
* @param index 插入位置
* @param data 插入数据
* @return 返回插入后的链表头节点
*/
Node* insert(Node* head, int index, int data) {
// 如果链表为空,则将新节点作为头节点
if (head == nullptr) {
head = new Node(data);
return head;
}
// 如果插入位置为第一个节点,则将新节点作为头节点
if (index == 0) {
Node* newNode = new Node(data);
newNode->next = head;
return newNode;
}
// 递归找到要插入位置的前一个节点
head->next = insert(head->next, index - 1, data);
return head;
}
```
调用示例:
```
Node* head = nullptr;
head = insert(head, 0, 1);
head = insert(head, 1, 2);
head = insert(head, 2, 3);
head = insert(head, 1, 4);
printList(head);
```
输出结果:
```
1 -> 4 -> 2 -> 3 -> NULL
```