如何在链接列表中实现深度复制构造函数?

时间:2019-09-19 00:36:49

标签: c++ linked-list copy-constructor deep-copy

对于我当前正在解决的这个问题,我试图在此链接列表中创建一个方法,该方法执行从一个项目到另一个项目的深层复制。现在,该方法的内部为空,因为我一生都无法获得任何工作。有什么办法可以在下面注释的代码区域中获得一些帮助,以实现这种深层复制构造函数?谢谢。

#include <string>
#include <iostream>
#include <cstddef>

using std::string;

class Item { 

public:

  string s; 

  Item(const char *a_s = "") { 
    s = a_s;
  }

  Item(string a_s) {
    s = a_s;
  }
};


class List {

  private:

      class ListNode { 

        public: 
          Item item; 
          ListNode * next; 
          ListNode(Item i) { 
            item = i;
            next = nullptr;
          }
      }; 

      ListNode * head; 
      ListNode * tail;

  public:

      class iterator {

        ListNode *node;

      public:
        iterator(ListNode *n = nullptr) {
          node = n;
        }

        Item& getItem() { return node->item; } //Not sure how this works
        void next() { node = node->next; }
        bool end() { return node==nullptr; }

      };



  public:

      List() {
        head = nullptr;
        tail = nullptr; //Sets the head and tail
      }

      List(const List & copy) { //Trying to create a copy constructor right here.

      }

      bool empty() { //Tells you if the list is empty
        return head==nullptr;
      }

      void append(Item a) { 

        ListNode *node = new ListNode(a);
          if ( head == nullptr ) {
            head = node;
            tail = node;
          } else {
            tail->next = node;
            tail = node;
          }
      }

      bool remove (Item &copy);

      void traverse() {
        ListNode *tmp = head;
        while(tmp != nullptr) {
          tmp = tmp->next;
        }
      }

      iterator begin() const {
        return iterator(head);
      }

};

    bool List::remove(Item &copy)
    {
      if (!empty()) {
        copy = head->item;
        ListNode *tmp = head->next;
        delete head;
        head = tmp;
        if (head==nullptr)
          tail = nullptr;
        return true;
      }
      return false;
    }


int main() {
   List l;
   l.append("eggs");

   List l2 = l; 

   std::cout << "done.\n";

   return 0;
}

1 个答案:

答案 0 :(得分:1)

假设append()正常工作,您可以为copy中的每个项目循环地反复调用它。

考虑到您如何使用tail指针实现链接列表,这种方法使其成为理想的解决方案。您编写了append函数,因此只需以战略性方式使用它即可。

但是请注意,如果您在没有尾指针的情况下实现了链表(您必须遍历到列表的末尾到append),则此方法仍然有效,但效率极低并不令人满意。

这里是一个示例(未经测试):

List(const List & copy) : head(nullptr), tail(nullptr) 
{ 
     ListNode *copyNode = copy.head;
     while (copyNode)
     {
         append(copyNode->item);
         copyNode = copyNode->next;
     }
 }

请注意,这没有针对边界条件进行测试,因此您可能需要检查copy是否为空,然后才能通过循环。

Here is an example that works for a simple case

相关问题