复杂链表的复制过程如下图所示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
typedef int DataType;
typedef struct ComplexNode{
DataType data;
struct ComplexNode* next;
struct ComplexNode* random;
}ComplexNode;
ComplexNode* BuyComplexNode(DataType d)
{
ComplexNode* temp = (ComplexNode*)malloc(sizeof(ComplexNode));
if (temp == NULL){
perror("use mallloc");
exit(EXIT_FAILURE);
}
memset(temp, 0, sizeof(ComplexNode));
temp->data = d;
temp->next = NULL;
temp->random = NULL;
return temp;
}
void PrintComplexList(ComplexNode* p)
{
while (p != NULL){
printf("%d->%d ", p->data, p->random->data);
p = p->next;
}
printf("\n");
}
ComplexNode* CopyComplexList(ComplexNode *head)
{
ComplexNode* cur = head;
ComplexNode* ptr = NULL;
ComplexNode* newhead = NULL;
//复制节点,并串成一条链
if (cur == NULL)
{
return NULL;
}
while (cur != NULL)
{
ptr = cur;
ComplexNode* temp = NULL;
temp = BuyComplexNode(cur->data);
cur = cur->next;
ptr->next = temp;
temp->next = cur;
}
//复制随机指针
cur = head->next;
ptr = head;
while (cur->next != NULL)
{
cur->random = ptr->random->next;
ptr = ptr->next->next;
cur = cur->next->next;
}
cur->random = ptr->random->next;
//将混合链分开
cur = head->next;
ptr = head;
newhead = head->next;
while (cur->next != NULL)
{
ptr->next = cur->next;
ptr = ptr->next;
cur->next = ptr->next;
cur = cur->next;
}
ptr->next = NULL;
return newhead;
}
void test8(){
ComplexNode* head = NULL;
ComplexNode* temp = NULL;
temp = BuyComplexNode(1);
head = temp;
temp = BuyComplexNode(2);
head->next = temp;
temp = BuyComplexNode(3);
head->next->next = temp;
temp = BuyComplexNode(4);
head->next->next->next = temp;
head->random = head->next->next;
head->next->random = head;
head->next->next->random = head->next;
head->next->next->next->random = head->next->next;
PrintComplexList(head);
CopyComplexList(head);
PrintComplexList(head);
}
int main(){
test8();
system("pause");
return 0;
}
欢迎各位批评指正!