题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路分析
- 用一个HashMap存储原来的结点情况,key为源节点,value设为跟源节点一样的副本结点。循环链表,根据map建立next和rand联系。
- 原地修改。
- 复制一个新的节点在原有节点后。eg.1 -> 2 -> 3 -> null 变成 1 -> 1 -> 2 -> 2 -> 3 - > 3 -> null。
- 从头遍历链表, cur.next.random = cur.random.next将复制节点的随机指针串起来。
- 最后将复制的链表一分为二。
代码实现
public RandomListNode Clone(RandomListNode pHead) {
HashMap<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode cur = pHead;
while (cur != null) {
map.put(cur, new RandomListNode(cur.label));
cur = cur.next;
}
cur = pHead;
while (cur!=null){
map.get(cur).next=map.get(cur.next);
map.get(cur).random=map.get(cur.random);
cur=cur.next;
}
return map.get(pHead);
}
//力扣上的原地修改做法
public Node copyRandomList(Node head) {
if (head == null) {
return head;
}
// 完成链表节点的复制
Node cur = head;
while (cur != null) {
Node copyNode = new Node(cur.val);
copyNode.next = cur.next;
cur.next = copyNode;
cur = cur.next.next;
}
// 完成链表复制节点的随机指针复制
cur = head;
while (cur != null) {
if (cur.random != null) { // 注意判断原来的节点有没有random指针
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
// 将链表一分为二
Node copyHead = head.next;
cur = head;
Node curCopy = head.next;
while (cur != null) {
cur.next = cur.next.next;
cur = cur.next;
if (curCopy.next != null) {
curCopy.next = curCopy.next.next;
curCopy = curCopy.next;
}
}
return copyHead;
}