定义一个简单的复杂链表。
注意
1.复杂链表的复制先处理复杂链表为空,这之间返回。
2.当复杂链表不为空,复制链表需要在原链表每个节点连接处插入新结点。
3.新结点随机指针域,(随机指针域为原结点随机指针域的下一个节点。
4.将新链表从原链表上拆下。
#include <stdlib.h>
#include <assert.h>
typedef struct CLNode {
int data;
struct CLNode *random;
struct CLNode *next;
} CLNode;
static CLNode * ComplexCreateNode(int data)
{
CLNode *node = (CLNode *)malloc(sizeof(CLNode));
node->data = data;
node->random = NULL;
node->next = NULL;
return node;
}
CLNode * Copy(CLNode *list)
{
CLNode *cur = list;
// 1. 复制结点
while (cur != NULL) {
CLNode *newNode = ComplexCreateNode(cur->data);
newNode->next = cur->next;
cur->next = newNode;
// 不能直接去 next
cur = cur->next->next;
}
// 2. 复制 random
cur = list;
while (cur != NULL) {
if (cur->random != NULL) {
cur->next->random = cur->random->next;
}
cur = cur->next->next;
}
// 3. 拆分
cur = list;
CLNode *newList = cur->next; // 保存新链表
while (cur != NULL) {
CLNode *node = cur->next;
cur->next = node->next;
if (cur->next != NULL) {
node->next = cur->next->next;
}
else {
node->next = NULL;
}
// 注意
cur = cur->next;
}
return newList;
}
void PrintComplexList(CLNode *list)
{
for (CLNode *cur = list; cur != NULL; cur = cur->next) {
printf("[%d, random(%p)->%d] ", cur->data,
cur->random,
cur->random ? cur->random->data : 0);
}
printf("\n");
}
void TestComplex()
{
CLNode *n1 = ComplexCreateNode(1);
CLNode *n2 = ComplexCreateNode(2);
CLNode *n3 = ComplexCreateNode(3);
CLNode *n4 = ComplexCreateNode(4);
n1->next = n2;
n2->next = n3;
n3->next = n4;
n1->random = n3;
n2->random = n1;
n3->random = n3;
CLNode *newList = Copy(n1);
PrintComplexList(n1);
PrintComplexList(newList);
}
int main()
{
TestComplex();
return 0;
}