简体   繁体   English

复制 SkipList / Linked List

[英]Copying a SkipList / Linked List

In the programming assignment, I need to clone a linked list (its a copy constructor so not returning anything but cloning).在编程任务中,我需要克隆一个链表(它是一个复制构造函数,所以除了克隆之外不返回任何东西)。 The old linked list will be going through some removing and adding elements but the new cloned linked list should remain untouched.旧链表将经历一些删除和添加元素,但新克隆的链表应保持不变。 How do I do that?我怎么做? When I remove and add new nodes to the old list, it also does the same for the new linked list.当我删除新节点并将其添加到旧列表时,它也会对新链表执行相同的操作。 How can I avoid this?我怎样才能避免这种情况?

  this->head = other.head;
  this->head->val = other.head->val;

  SNode *curr = other.head->next;
  SNode *newCurr = nullptr;
  while (curr != nullptr) {
    newCurr = curr;
    curr = curr->next;
  }
}

I have tried the above code, but when I modify the old list, ie, adding and removing nodes, it also adds and removes nodes from the new list.我试过上面的代码,但是当我修改旧列表时,即添加和删除节点时,它也会在新列表中添加和删除节点。 What can I do to avoid the modifications happening on the new list?我该怎么做才能避免在新列表中发生修改?

Your code is not creating new nodes, so this cannot work.您的代码没有创建新节点,因此这行不通。 A cloned list should consist of new nodes, so the SNode constructor should be called.克隆列表应包含新节点,因此应调用SNode构造函数。

For instance:例如:

this->head = other.head;

This will just make the new list point to the same list: now you have two head pointers pointing to the same head node.这只会使新列表指向同一个列表:现在你有两个head指针指向同一个头节点。 And then, by consequence, the following assignment doesn't do anything useful, as it really is assigning a member's own value to itself:然后,结果,下面的赋值没有做任何有用的事情,因为它实际上是将成员自己的值赋给自己:

this->head->val = other.head->val;

The loop isn't doing anything useful either, as it is not assigning anything to any member that belongs to the new structure.该循环也没有做任何有用的事情,因为它没有将任何东西分配给属于新结构的任何成员。 It only assigns to variables, walking through the original list with two variables, where newCurr follows one step behind curr .它只分配给变量,遍历带有两个变量的原始列表,其中newCurr落后于curr一步。

Here is a correction of your snippet:这是您的代码段的更正:

  // Deal with boundary case: empty list
  this->head = NULL;
  if (other.head == NULL) return; // Nothing more to do.
  
  // Clone the head node
  this->head = new SNode(other.head->val);

  SNode *curr = other.head->next;
  SNode *tail = this->head; // tail is a more descriptive name
  while (curr != nullptr) {
    tail->next = new SNode(curr->val); // Clone current node and append it
    tail = tail->next; // This new node is now the tail
    curr = curr->next;
  }

This assumes you have an SNode constructor that takes a single argument for the node's value.这假定您有一个SNode构造函数,该构造函数采用节点值的单个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM