//剑指offer:复杂链表的复制(复制一个包含random域的链表,random域随机的指向链表中任意节点)
//思路:先复制出链表的next结构并且将自己对应的值和自身放入map中
// 再复制random域,通过将之前链表的random域的值取出来,然后去map中找新链表对应的结点,并赋值。
// 注意不要错误的使用之前的链表节点。画图让思路更清楚。
#include "stdafx.h"
#include"map"
using namespace std;
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
RandomListNode* Clone(RandomListNode* pHead)
{
if (pHead == NULL)
return NULL;
RandomListNode* clon = pHead;
RandomListNode* clon_head = NULL;
RandomListNode* last_node = NULL;
map<int, RandomListNode*> ma;
while (clon != NULL) {
RandomListNode *tmp = new RandomListNode(clon->label);
if (clon_head == NULL) {
clon_head = tmp;
}
if (last_node != NULL)
last_node->next = tmp;
last_node = tmp;
ma.insert(make_pair(tmp->label, tmp));
//tmp->random = clon->random;
clon = clon->next;
}
clon = clon_head;
RandomListNode *clon2 = pHead;
while (clon != NULL) {
/*tmp->next = clon->next; //这里错误的使用了以前链表的结点
tmp->random = ma[clon->label];
clon = clon->next; */
if (clon2->random != NULL)
clon->random = ma[clon2->random->label];
clon2 = clon2->next;
clon = clon->next;
}
return clon_head;
}
int main()
{
RandomListNode *head = NULL;
RandomListNode *test = NULL;
RandomListNode *tmp = NULL;
for (int i = 0; i < 5; i++) {
tmp = new RandomListNode(i);
if (test != NULL)
test->next = tmp;
test = tmp;
if (i == 0)
head = tmp;
}
for (int j = 0; j < 5; j++) {
RandomListNode *node = head;
for (int z = 0; z < j; z++)
node = node->next;
tmp = node;
if (tmp->next == NULL)
tmp = head;
else
tmp = tmp->next;
if (tmp->next == NULL)
tmp = head;
else
tmp = tmp->next;
node->random = tmp;
}
RandomListNode *temp = head;
while (temp) {
printf("%d %d\n", temp->label, temp->random->label);
temp = temp->next;
}
RandomListNode *head2 = Clone(head);
while (head2) {
printf("%d %d\n", head2->label,head2->random->label);
head2 = head2->next;
}
return 0;
}