[英]inserting node at ith position in linked list recursively
将帮助我解决这个问题我正在尝试使用递归将节点插入到链表中的第 i 个位置
这是代码,请帮助我改进代码,当我必须返回头部时,我最后特别面临的问题我不知道如何返回
Node* insertNodeRecursively(Node*head, int n, int data)
{
if(head == nullptr)
{
return head;
}
else if(n==0)
{
Node* newNode= new Node(data);
newNode->next = head->next;
head->next = newNode;
return head;
}
Node * x = insertNodeRecursively(head->next,n-1,data);
}
所以我猜你想要 function insertNodeRecursively
返回新的头,对吧? 如果不考虑在调用者 function 中插入 position 0 的特殊情况,其他任何事情都将不起作用。
您可以执行以下操作:
if (n == 0) {
Node *newNode = new Node(data);
newNode->next = head;
return newNode;
}
if (head == nullptr) {
return nullptr;
}
Node *node = insertNodeRecursively(head->next, n - 1, data);
head->next = node;
return head;
这个想法是,当这不是要插入的 position 时,我们需要假设下一个递归调用可能会给我们一个新的头(从那个 position 开始),所以我们需要那个head->next = node;
任务。 调用作为第一个参数传递的节点head
可能会造成混淆,因为它并不总是列表的头部(仅在递归开始时)。 在 n 为 0 的情况下,它是您要在其前面插入的节点。您在n == 0
情况下编写的问题是您总是返回旧头,即使您应该返回newNode
。 head
节点应该是newNode
之后的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.