复杂链表的复制
复杂链表不仅包括数据域和指针域,还包括一个random域,并且该域可以为空。
复杂链表的拷贝主要分为三步:
(1)拷贝原始链表的每一个节点,插入到当前节点的后面。
(2)调整random指针
(3)分离两个链表
代码实现:
#include
#include
typedef int DataType;
typedef struct ComplexNode
{
DataType _data;
struct ComplexNode* _next;
struct ComplexNode* _random;
}ComplexNode, *pComplexNode, *pComplexList;
pComplexNode CreateComplexNode(DataType x)
{
pComplexNode tmp = (pComplexNode)malloc(sizeof(ComplexNode));
if (tmp == NULL)
{
perror("malloc");
return NULL;
}
tmp->_data = x;
tmp->_next = NULL;
tmp->_random = NULL;
return tmp;
}
void Printf(pComplexList s1)
{
pComplexNode cur = s1;
while (cur)
{
printf("[%d]->random->", cur->_data);
if (cur->_random)
{
printf("[%d]-->", cur->_random->_data);
}
else
{
printf("NULL-->");
}
cur = cur->_next;
}
}
pComplexList CloneComplex(pComplexList plist)
{
//拷贝原始链表的每一个节点,插入到当前节点的后面
pComplexNode cur = plist;
pComplexNode s1 = NULL;
pComplexNode s2 = NULL;
pComplexNode tail = NULL;
while (cur)
{
pComplexNode tmp = CreateComplexNode(cur->_data);
tmp->_next = cur->_next;
cur->_next = tmp;
cur = cur->_next->_next;
}
//调整random指针
cur = plist;
while (cur)
{
cur->_next->_random = cur->_random->_next;
cur = cur->_next->_next;
}
//分离两个链表
s1 = plist;
if (s1)
{
s2 = s1->_next;
tail = s2;
}
while (tail->_next)
{
s1->_next = tail->_next;
s1 = s1->_next;
tail->_next = s1->_next;
tail = tail->_next;
}
s1->_next = NULL;
return s2;
}
void Test()
{
pComplexList l1;
pComplexNode cur1 = CreateComplexNode(1);
pComplexNode cur2 = CreateComplexNode(2);
pComplexNode cur3 = CreateComplexNode(3);
pComplexNode cur4 = CreateComplexNode(4);
cur1->_next = cur2;
cur2->_next = cur3;
cur3->_next = cur4;
cur1->_random = cur4;
cur2->_random = cur1;
cur3->_random = cur2;
cur4->_random = cur3;
l1 = CloneComplex(cur1);
Printf(cur1);
printf("\n");
Printf(l1);
}