且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 C++ 中编写一个函数来复制链表

更新时间:2023-11-23 21:50:46

您需要问自己的第一个问题是复制语义是什么.特别是,您使用 Student* 作为节点内容.复制节点内容是什么意思?我们应该复制指针以便两个列表指向(共享)相同的学生实例,还是应该执行 深拷贝?

The first question you need to ask yourself is what the copy semantics are. In particular, you're using a Student* as node contents. What does copying node contents mean? Should we copy the pointer so that the two lists will point to (share) the same student instances, or should you perform a deep copy?

struct Listnode {    
  Student *student; // a pointer?  shouldn't this be a `Student` object?
  Listnode *next;
};

您应该问自己的下一个问题是如何为第二个列表分配节点.目前,您只在副本中分配了 1 个节点.

The next question you should ask yourself is how you will allocate the nodes for the second list. Currently, you only allocate 1 node in the copy.

我认为你的代码应该看起来更像:

I think you code should look more like:

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;
}

如果您更喜欢在两个列表之间共享学生实例,可以使用


If you prefer sharing student instances between the two lists, you can use

copy->student = current->student;

代替

copy->student = new Student(*current->student);