对于如何在双向链表上实现副本分配有些困惑。我设法使复制构造函数正常工作,但是我不确定分配如何。我试图在没有复制和交换方法的情况下执行此操作。
List.H
class List
{
public:
List();
~List();
List(const List& c);
List& operator= (const List& t);
private:
List *Next;
List *Prev;
Node *Head;
List.cpp
List::~List()
{
Node* move = Head;
while (move!=NULL)
{
Node *temp = move->Next;
delete move;
move = temp;
}
}
List::List(const List& c)
{
name = c.name;
Prev = c.Prev;
Next = c.Next;
Node* dummy, * current;
Head= dummy = new Node();
current = c.Head;
while (current)
{
dummy->Next = new Node(*current);
current = current->Next;
dummy = dummy->Next;
}
Node* temp = Head;
Head = Head->Next;
delete temp;
}
List& List::operator=(const List& t)
{
Next = t.Next;
return *this;
}
我还必须遍历赋值运算符中的每个节点吗?
编辑这就是我现在所拥有的。问题是当我从列表中获取数据时,它为空。
List& List::operator=(const List& that)
{
if (this != &that)
{
while (Head)
{
Node* temp = Head;
Head = Head->Next;
delete temp;
}
Node* dummy, * current;
Head = dummy = new Node();
current = that.Head;
while (current)
{
dummy->Next = new Node(*current);
current = current->Next;
dummy = dummy->Next;
}
dummy->Next = nullptr;
}
return *this;
}
简单回答是。
List L1;
List L2(L1);
List L1;
List L2;
L2 = L1;
[在两种情况下,都必须将L1
复制到L2
,并且复制或分配后L1
应该保持不变。因此,每个节点的内容都必须复制到新创建的节点。
复制构造函数看起来像这样:
List::List(const List& c)
{
Node start;
Node* dummy = &start;
while (c)
{
dummy->next = new Node(*c);//New node created with content of *c
dummy = dummy->Next;
c = c->Next;
}
dummy->next = nullptr;
Head = start.next;
}
和这样的赋值运算符:
List& List::operator=(const List& that)
{
if (this != &that) //avoid self assignment like List L1;L1=L1;
{
while (Head)//Delete exist nodes
{
Node* temp = Head;
Head = Head->Next
delete temp;
}
Node start;
Node* dummy = &start;
Node* thatHead = that.Head;
while (thatHead)
{
dummy->next = new Node(*thatHead);//New node created with content of *thatHead
dummy = dummy->Next;
thatHead = thatHead->Next;
}
dummy->next = nullptr;
}
return *this;
}