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);总结
以上是内存溢出为你收集整理的编写C中复制链表的功能全部内容,希望文章能够帮你解决编写C中复制链表的功能所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)