我需要实现一个名为copyList的辅助功能,它具有一个参数,一个指向ListNode的指针.此函数需要返回指向原始链接列表副本的第一个节点的指针.换句话说,换句话说,我需要在C中编写一个函数,该函数接收一个链表的头节点,并复制整个链表,返回一个指针到新的头节点.我需要帮助实现这个功能,这是我现在所拥有的.
Listnode *SortedList::copyList(Listnode *L) {
Listnode *current = L; //holds the current node
Listnode *copy = new Listnode;
copy->next = NULL;
//traverses the list
while (current != NULL) {
*(copy->student) = *(current->student);
*(copy->next) = *(current->next);
copy = copy->next;
current = current->next;
}
return copy;
}
此外,这是我正在使用的Listnode结构:
struct Listnode {
Student *student;
Listnode *next;
};
注意:使用此函数的另一个因素是将指针返回到局部变量的想法.
解决方法
你需要问自己的第一个问题是复制语义是什么.特别是,您正在使用Student *作为节点内容.复制节点内容是什么意思?我们应该复制指针,以便这两个列表将指向(共享)相同的学生实例,还是应该执行一个
deep copy?
struct Listnode {
Student *student; // a pointer? shouldn't this be a `Student` object?
Listnode *next;
};
您应该问自己的下一个问题是如何为第二个列表分配节点.目前,您只能在副本中分配1个节点.
我想你的代码应该更像:
Listnode *SortedList::copyList(Listnode *L) {
Listnode *current = L;
// Assume the list contains at least 1 student.
Listnode *copy = new Listnode;
copy->student = new Student(*current->student);
copy->next = NULL;
// Keep track of first element of the copy.
Listnode *const head = copy;
// 1st element already copied.
current = current->next;
while (current != NULL) {
// Allocate the next node and advance `copy` to the element being copied.
copy = copy->next = new Listnode;
// copy the node contents; don't share references to students.
copy->student = new Student(*current->student);
// No next element (yet).
copy->next = NULL;
// Advance 'current' to the next element
current = current->next;
}
// Return pointer to first (not last) element.
return head;
}
如果您喜欢在两个列表之间共享学生实例,可以使用
copy->student = current->student;
代替
copy->student = new Student(*current->student);