思路1:
#include<iostream>
using namespace std;
//基础方法
//核心思想 将链表转化为数组进行看待
//random指针 指的就是数组里面第几个元素
//我的思路 拆为三部分进行实现
//第一部分 遍历一遍链表得到每个random所对应的链表所在位置 通过t数组记录一下
//第二部分 实现除了random以外的链表部分的复制 这步很简单
//第三部分 在第二部分实现的复制链表上 应用第一部分random得到所对应链表所在位置的解 将其正确连接
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
class Solution {
private:
Node* newhead,*p1,*p2;
int t[10000]={0};
int count1=0;//记录第几个节点
int count2=0;//记录每个节点中random 对应从头指针开始的第几个节点 头指针默认为编号0 第一个为1 题目提示的有
public:
Node* copyRandomList(Node* head) {
if(head==NULL)//如果为空指针 直接返回空就行了
return newhead;
//第一大部分 找到每个random所对应的位置 将其 存在t数组里面
Node* head1=head;//新建一个头指针 避免原head改变
while(head1!=NULL)//进行遍历
{
Node*head2=head;//新建第二个指针 t数组所记录的就是从头指针算起 到底是第几个
count2=0;//每次遍历都要从头指针0开始
while(1)
{
if(head2==head1->random)//如果找到了
{
t[count1++]=count2;//记录下是第几个
break;//退出
}
else
{
head2=head2->next;//没找到 head2和count2就继续往下数
count2++;//继续往下数
}
}
head1=head1->next;//当前节点的找到了 找下一个节点
}
//第二大部分 除了random指向以外的 链表其他部分的完全复制 较为简单不再赘述
Node *head2=head,*p1,*p2;
int tmi=0;
while(head2!=NULL)
{
tmi++;
p2=(Node*)malloc(sizeof(Node));
p2->val=head2->val;
if(tmi==1)
{
newhead=p1=p2;
head2=head2->next;
continue;
}
p1->next=p2;
p1=p2;
head2=head2->next;
}
p1->next=NULL;
//第三大部分 在第二部分实现的复制链表上 应用第一部分random得到所对应链表所在位置的解 将其正确连接
Node*head3=newhead;//取得第二部分得到的链表头
for(int i=0;i<count1;i++)//对数组t中每个元素进行遍历 即对head链表每个节点遍历
{
Node *head4=newhead;//同样的 每次从头指针开始算起
for(int j=0;j<t[i];j++)
{
head4=head4->next;//t数组中记录了当前节点所指向的是第几个元素 那么就直接往后数几位就行了
}//比如说如果t[i]=0 则表示第i个元素节点的random指针指向了从head算起的第0个元素 即自身
head3->random=head4;//链接
head3=head3->next;//找下一个节点
}
//复制完毕 返回即可
return newhead;
}
};
思路2:
#include<iostream>
#include<unordered_map>
using namespace std;
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
//核心思想 1.将这种列表和树进行类比 递归进行建立
//2. 遇到了不能用数组表达这个节点是否建立或者遍历过的时候 可以用哈希表进行判断 哈希表和以前的那种judge数组判断是否遍历过本质都是一种对应关系
// class Solution {
// public:
// unordered_map<Node*, Node*> cachedNode;//起到了我平时使用的judge的作用 看有没有被创建
// Node* copyRandomList(Node* head) {
// if (head == nullptr) {
// return nullptr;
// }
// if (!cachedNode.count(head)) {//如果没有被创建
// Node* headNew = new Node(head->val);
// cachedNode[head] = headNew;//设定为创建 即true
// headNew->next = copyRandomList(head->next);
// headNew->random = copyRandomList(head->random);
// }
// return cachedNode[head];
// }
// };
class Solution {
private:
unordered_map<Node*,Node*> judge;
public:
Node* copyRandomList(Node* head) {
if(head==NULL)
{
return;
}
else if(judge[head]==NULL)
{
Node* newhead=new Node(head->val);//C++开辟堆区的方法 比C好用
judge[head]=newhead;
newhead->next=copyRandomList(head->next);
newhead->random=copyRandomList(head->random);
return newhead;
}
return judge[head];
}
};