【发布时间】:2021-02-25 18:16:43
【问题描述】:
下面的函数是我正在尝试处理的函数。我遇到的问题是我不知道如何将指向原始头的指针“保留”到列表中,因为这是插入后我必须返回的。
没有驱动代码,所以一切都必须在这个函数中完成。
因为我必须递归地执行此操作,所以我不能只创建一个临时节点来指向原始头。我刚刚习惯了递归,我找不到解决方案。
注意:我的函数还有一些其他问题,因为我认为在链表的开头和结尾插入新节点时效果不佳,但我相信我可以解决这些边缘情况。
我要学习的主要内容是如何“存储”我列表的原始头部。
感谢所有帮助。
Node* insert(Node* head, int index, int data)
{
if (head == NULL) return NULL; // if list is empty
if (index == 1) // if we have accessed node before insertion
{
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->next = head->next; // new_node->next now links to the node next in the list
head->next = new_node; // head->next links to new node
new_node->data = data; // assigns new node its data
return head; // not sure how to return original head
}
return insert(head->next, index - 1, data);
}
【问题讨论】:
标签: c recursion linked-list singly-linked-list function-definition