gpt4 book ai didi

c++ - 使用节点的深度复制和解构器哨兵链表

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:59:00 26 4
gpt4 key购买 nike

我目前正在使用节点制作链表程序(我不知道任何其他方式)并且我遇到了关于创建深层拷贝并使用我的 ~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;
}
}
}

我正在寻求有关此代码的建议和评论,以了解下一步如何进行或如果出现严重错误应该更改什么!

最佳答案

链表是允许任何类型的变量位于其中的模板。老实说,你最好使用 std::list这需要 #include <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;
}

至于析构函数,您只需要遍历列表并删除节点即可:

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

我试图让评论澄清任何可能不清楚的地方。

关于c++ - 使用节点的深度复制和解构器哨兵链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12945941/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com