深层复制和解构器前哨链接列表使用节点

Deep copy and deconstructor sentinel linked list using Nodes

本文关键字:列表 链接 节点 前哨 复制 和解      更新时间:2023-10-16

我当前正在使用节点制作链接列表程序(我不知道任何其他方式),我遇到了一个关于创建深层副本并摆脱所有节点的问题和哨兵与我的〜list()。删除节点不是问题,但是哨兵是因为第一个未分配索引值。

List::~List()
{
  for(size_t i=0; i<size; i++)
    {
      _setCurrentIndex(i);
      if(current && curent->next == NULL)
    {
      Node *temp = current->next;
      delete temp;
      delete current;
    }
      else
    {
      Node *old = current;
      current = current->next;
      delete old;
    }
    }
}
List::List(const List & orig)
{
for(size_t i=0; i<size; i++)
{
 if(i==0)
  {
   Node *copyFront = new Node; //the first sentinel
   copyFront->data = orig.front->data; //front is defined in private in list.h
   copyFront->prev = NULL; // it is defined as a Node (same for rear)
  }
 else if(0<=i && i<size) //put in i<size b/c 0<=i would always be true
  {
   _setCurrentIndex(i) //sets what current is and currentIndex which pts to diff Nodes
   Node *copy = new Node;
   copy->data = current->data; 
   copy->next = current->next;
   current = current->next;
  }
 else if(i+1 == size)
  {
   Node *copyRear = new Node; //making the last sentinel, but it has to be
   copyRear->data = orig.rear->data; //after data Node
   copyRear->next = NULL;
  }
 }
}

我正在寻求有关此代码的建议和评论,以了解如何进行下一步操作,或者如果某事可怕地错了!

链接列表是模板,允许任何类型的变量坐在其中。我的诚实认为,最好使用需要#include <list>标头文件的std::list

当然,如果您真的想要自己编写链接列表类的经验,那么以下代码将成为列表的深刻副本:

List::List( const List& other) {
    if( other.head_ != nullptr) {
        head_ = new Node( other.head_->item_);  // copy first node
        assert( head_ != nullptr);  // ensure that the memory was allocated correctly
        // copy the rest of the list
        Node* pnew = head_;
        // loop through the list until you reach the end (i.e. a node that's nullptr)
        for( Node* porig( other.head_->next_); porig != nullptr; porig = porig->next_) {
            // assign the next node in the destination list to the next node in the paramter's list
            pnew->next_ = new Node( porig->item_);
            assert( pnew->next_ != nullptr);  // ensure that the memory was allocated correctly
            pnew = pnew->next_;  // move onto the newly created node in the destination list
        }
    }
    else
        // if the parameter is empty then the destination list will be empty as well
        head_ = nullptr;
}

至于destuructor,您只需要在删除节点的列表中运行:

List::~List() {
    while( head_ != nullptr) {  // keep looping until the list gets to the end
        // make a second pointer to the node you are about to delete (so you don't lose track of it)
        Node* pn( head_);
        // move the head_ onto the next node essentially "removing" the first node from your list
        head_ = head_->next_;
        // delete the node that you've just "removed" from your list
        delete pn;
    }
}

我试图使评论清除所有可能不清楚的内容。