请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
示例
示例一
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例二
输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]
示例三
输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]
示例四
输入:head = []
输出:[]
解释:给定的链表为空(空指针),因此返回 null。
方法一 利用hashMap记录节点
我们在遍历的时候,可能会遇到当前节点的random还没有创建的情况,因此,我们首先遍历链表,创建好需要的节点,用hashMap存储这些节点,key为原节点,value为新创建的节点。后面每次查找都可以以原节点为索引
1、首先遍历链表,将新建节点put进hashMap
Node cur = head;
Map<Node,Node> map = new HashMap<>();
while(cur != null)
{
map.put(cur,new Node(cur.val));
cur = cur.next;
}
2、设置新节点的next和random
cur = head;
Node res = map.get(cur);
while(cur != null)
{
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
3、代码
public Node copyRandomList(Node head) {
if(head == null)
{
return null;
}
Node cur = head;
Map<Node,Node> map = new HashMap<>();
while(cur != null)
{
map.put(cur,new Node(cur.val));
cur = cur.next;
}
cur = head;
Node res = map.get(cur);
while(cur != null)
{
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
return res;
}
方法二、拼接与拆分
解析
考虑构建‘原节点 1 -> 新节点 1 -> 原节点 2 -> 新节点 2 -> ……’的拼接链表,
这样就可以便捷的访问next和random
程序流程
- 复制各节点,构建拼接链表
Node cur = head;
while(cur != null)
{
Node temp = new Node(cur.val);
temp.next = cur.next;
cur.next = temp;
cur = cur.next.next;
}
- 遍历链表,为新节点设置random
cur = head;
while(cur != null)
{
//新节点的random不能指向原节点的random
if(cur.random != null)
{
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
- 拆分链表,将链表拆分为原链表和新链表
cur = head.next;
Node pre = head;
while(cur.next != null)
{
pre.next = pre.next.next;
cur.next = cur.next.next;
pre = pre.next;
cur = cur.next;
}
代码
class Solution {
public Node copyRandomList(Node head) {
if(head == null)
{
return null;
}
Node cur = head;
while(cur !=null)
{
Node newCur = new Node(cur.val);
newCur.next = cur.next;
cur.next = newCur;
cur = cur.next.next;
}
cur = head;
while(cur != null)
{
if(cur.random != null)
{
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
cur = head.next;
Node res = head.next;
Node pre = head;
while(cur.next != null)
{
pre.next = pre.next.next;
cur.next = cur.next.next;
cur = cur.next;
pre = pre.next;
}
pre.next =null;
return res;
}
}