对于一个复杂链表,可以定义为每个结点除了有一个next指针指向下一个结点外,还有一个random指针指向链表中的任意一个结点或者NULL。
本文中有关复杂链表结点结构体和创建结点接口定义如下:
typedef struct ComplexNode {
int data;
struct ComplexNode *next;
struct ComplexNode *random;
} CN;
CN * CreateNode(int data)
{
CN *node = (CN *)malloc(sizeof(CN));
node->data = data;
node->random = node->next = NULL;
return node;
}
然后定义了一个CNInit函数来初始化创建一个复杂链表,代码如下:
CN * CNInit()
{
CN *n1 = CreateNode(1);
CN *n2 = CreateNode(2);
CN *n3 = CreateNode(3);
CN *n4 = CreateNode(4);
n1->next = n2; n2->next = n3; n3->next = n4;
n1->random = n3; n2->random = n1; n3->random = n4;
return n1;
}
创建的复杂链表如图所示:
对于复杂链表的复制,通过以下三个步骤完成:
(1)根据原链表的每个结点node创建对应的结点newnode,然后将每个结点newnode连接到node的后面(n为原node结点,m为newnode结点)。
(2)复制random指针部分。例如n1的random指针指向n3,同样复制后m1的random指针指向m3。
(3)把第二步得到的链表拆分为两个链表,奇数位置上的node结点组成原始链表,偶数位上得到newnode结点组成新链表。
代码如下:
void Copy(CN *list)
{
// 复制链表每个结点,让新的结点跟在老的结点后边
CN *cur = list;
CN *newNode;
// cur 只遍历老的结点
while (cur != NULL) {
newNode = CreateNode(cur->data);
newNode->next = cur->next;
cur->next = newNode;
cur = newNode->next;
}
// 复制 random 字段
cur = list;
while (cur != NULL) {
newNode = cur->next;
if (cur->random != NULL) {
newNode->random = cur->random->next;
}
cur = cur->next->next;
}
//分离两个链表
cur = list;
CN *next, *newNext;
CN *result = list->next;
while (cur != NULL) {
newNode = cur->next;
next = newNode->next;
if (next == NULL) {
newNext = NULL;
}
else {
newNext = next->next;
}
cur->next = next;
newNode->next = newNext;
cur = next;
}
printf("复制成功\n");
}