[英]Copying a linked list to a reference to a linkedlist
I have been assigned to pass a pointer to a linked list and copy that to a new list passed as a pointer to a linked list, and copy it recursively. 我被分配了一个指向链表的指针,并将其复制到作为链表的指针传递的新列表,然后递归复制它。 I receive a segmentation fault when trying to copy the very first item.
尝试复制第一项时收到分段错误。
I've tried every combination of pointer and reference I can think of while maintaining the program requirements of the function prototype: void duplicate(node * head, node *& newHead) 我在维持函数原型的程序要求的同时尝试了指针和引用的每种组合:voidplicate(node * head,node *&newHead)
#include <iostream>
#include "supplied.o"
using namespace std;
struct node
{
int data;
node * next;
};
int main()
{
node * head = NULL;
build(head); // supplied function initializes list
newHead = NULL;
duplicate (head, newHead);
}
void duplicate (node * head, node*& newHead)
{
node * iterator1 = NULL;
node * iterator2 = new Node;
node * iterator2 = newHead;
iterator2->data = iterator1->data; //error occurs here
// program will continue to copy list recursively
}
void build (node *& head) //cannot see this function; provided via "supplied.o"
{
}
the error occurs because the function is unable to access iterator2->data. 发生错误是因为函数无法访问iterator2-> data。 Iterator1->data can be accessed and even printed without problem.
可以访问Iterator1->数据,甚至可以毫无问题地进行打印。
Just create a new node, then copy the data, then recurse with the next
nodes. 只需创建一个新节点,然后复制数据,然后递归
next
节点即可。 Take care of null pointers. 注意空指针。 That's all.
就这样。
duplicate(const node*head, node* &newhead)
{
if(head) {
// copy a valid node
newhead = new node; // allocate a new node
newhead->data = head->data; // copy the data
duplicate(head->next, newhead->next); // recurse on the next node
} else
// in case of null pointer: terminate recursion
newhead = nullptr;
}
Now, consider what happens step-by-step if you call duplicate
with a long list and convince yourself that it actually does what you want. 现在,考虑一下如果您用一个很长的列表调用
duplicate
,并说服自己它确实可以完成您想要的操作,那么逐步进行的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.