对于链表的复制见的也比较多了,但对于复杂链表的复制,主要存在的问题是复杂链表中节点存在random指针,但它指向的方向是任意的,因此在对复杂链表进行复制的过程中,对于确定random指针的指向还存在着很大的问题。
解决这个问题的一个方法是,将原来链表的每个节点进行复制,而复制的节点就插入到原来节点的后面,这样复制节点的random指针指向,就是原来节点random指针指向的_next节点。代码实现如下:
typedef int DataType;
typedef struct ComplexNode
{
DataType _data;
struct ComplexNode *_next;
struct ComplexNode *_random;
ComplexNode(DataType data)
:_data(data)
, _next(NULL)
, _random(NULL)
{}
}ComplexNode;
ComplexNode *copy(ComplexNode *head)
{
//复制节点
ComplexNode *cur = head;
while (cur)
{
ComplexNode *tem = new ComplexNode(cur->_data);
tem->_next = cur->_next;
cur->_next = tem;
cur = tem->_next;
}
//找random
cur = head;
ComplexNode *tem;
while (cur)
{
tem = cur->_next;
if (cur->_random)
tem->_random = cur->_random->_next;
cur = tem->_next;
}
//分离
cur = head;
ComplexNode *newhead=NULL, *newtail=NULL;
if (cur)
{
newhead = newtail = cur->_next;
cur->_next = newhead->_next;
cur = cur->_next;
}
while (cur)
{
newtail->_next = cur->_next;
cur->_next = cur->_next->_next;
newtail = newtail->_next;
cur = cur->_next;
}
return newhead;
}
ComplexNode *Create()
{
ComplexNode *head1 = new ComplexNode(1);
ComplexNode *head2 = new ComplexNode(2);
ComplexNode *head3 = new ComplexNode(3);
ComplexNode *head4 = new ComplexNode(4);
head1->_random = head3;
head2->_random = head4;
head3->_random = head2;
head4->_random = NULL;
head1->_next = head2;
head2->_next = head3;
head3->_next = head4;
head4->_next = NULL;
return head1;
}
void print(ComplexNode *head)
{
while (head)
{
cout << head->_data << ":";
if (head->_random)
cout << head->_random->_data << " ";
else
cout << "NULL" << " ";
head = head->_next;
}
}
int main()
{
ComplexNode *ret = Create();
print(ret);
getchar();
return 0;
}
原文地址:http://10810512.blog.51cto.com/10800512/1764378