链表复制

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

 struct RandomListNode {
     int label;
     RandomListNode *next, *random;
     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 };

class Solution 
 {
    public:
void insert(RandomListNode* &list)
{
RandomListNode* temp = list;
RandomListNode* prev = nullptr;
int val;
int len = 0;
while (cin >> val)
{
if (!list)
{
list = new RandomListNode(val);
list->next = nullptr;
prev = list;
}
else
{
temp = new RandomListNode(val);
temp->next = prev->next;
prev->next = temp;
prev = temp;
}
len++;
}
temp = list;
while (temp)
{
findnode(list, temp->random, rand() % (len));
temp = temp->next;
}
}
int findindex(RandomListNode* list,RandomListNode* node)
{//到终点的距离
RandomListNode* temp = list;
int i = 1;
while (temp != node)
{
i++;
temp = temp->next;
}
//i++;
return i;
}
void findnode(RandomListNode* head,RandomListNode* &dest,int index)
{
int i = index;
if (index == 0)
dest= nullptr;
else if (index == 1)
dest = head;
else
{//距离源点的距离 做标记
//int t = i - 1;
for (int i = 1; i < index; i++)
{
head = head->next;
}
dest = head;
}
}//找到对应的节点
RandomListNode* copyRandomList(RandomListNode* pHead)
{
map<RandomListNode*, int> nodemap;
map<RandomListNode*, RandomListNode*> nodemap1;
RandomListNode* temp = pHead;
RandomListNode* head = nullptr;
//head->next = nullptr;
RandomListNode* prev = head;
RandomListNode* temp11 = nullptr;
//RandomListNode* temp = nullptr;
while (temp)
{
nodemap.insert(pair<RandomListNode*, int>(temp, findindex(pHead,temp->random)));
if (!head)
{
head = new RandomListNode(temp->label);
head->next = nullptr;
prev = head;
}
else
{
temp11 = new RandomListNode(temp->label);
temp11->next = prev->next;
prev->next = temp11;
prev = temp11;
}
temp = temp->next;//找到映射关系
}
//复制指针域
RandomListNode* temp1=pHead;
RandomListNode* temp2 = head;
while (temp1&&temp2)
{
findnode(head, temp2->random, nodemap[temp1]);
temp1 = temp1->next;
temp2 = temp2->next;
}
return head;
}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值