一个链表的每个节点,有一个指向next指针指向下一个节点,还有一个random指针指向这个链表中的一个随机节点或NULL,现在要求实现复杂这个链表,返回复制后的新链表。
/* CLNode.h */
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct CLNode
{
int data;
struct CLNode *random;
struct CLNode *next;
} CLNode;
CLNode *ComplexCreateNode(int data)
{
CLNode *node = (CLNode *)malloc(sizeof(CLNode));
node->data = data;
node->random = node->next = NULL;
return node;
}
CLNode *Copy(CLNode *list)
{
CLNode *cur = list;
//copy新节点
while (cur != NULL)
{
CLNode *NewNode = ComplexCreateNode(cur->data);
NewNode->next = cur->next;
cur->next = NewNode->next;
cur = cur->next->next;
}
//copy新的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 test()
{
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 = n4;
n3->random = n1;
n4->random = n2;
CLNode *newList = Copy(n1);
PrintComplexList(n1);
PrintComplexList(newList);
}
/* main.c */
#include "CLNode.h"
int main()
{
test();
system("pause");
return 0;
}