我对如何在双向链表上实现复制赋值有点困惑。我设法让复制构造函数工作,但我确定在分配上。我试图在没有复制和交换方法的情况下执行此操作。
列表.H
class List
{
public:
List();
~List();
List(const List& c);
List& operator= (const List& t);
private:
List *Next;
List *Prev;
Node *Head;
列表.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;
}
我是否还必须遍历赋值运算符中的每个节点?
编辑 这就是我现在所拥有的。问题是当 im 从列表中获取数据时,它是空的。
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;
Node* CurrentNode = c.Head;
while (CurrentNode)
{
dummy->next = new Node(*CurrentNode);//New node created with content of *CurrentNode
dummy = dummy->Next;
CurrentNode = CurrentNode->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;
}