提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
题目描述
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题过程
解题思路
1、利用哈希映射将源节点和新节点构成键值对。映射键所对应的值(即新链表节点)不具有next和random属性。
2、取出新链表节点,并为其赋予next和random属性。
3、返回新链表头节点即可。
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
Map<Node, Node> map = new HashMap<>();
Node cur = head;
while(cur != null){
map.put(cur, new Node(cur.val));
cur = cur.next;
}
Node curNew = map.get(head);
cur = head;
while(cur != null){
curNew.next = map.get(cur.next);
curNew.random = map.get(cur.random);
curNew = curNew.next;
cur = cur.next;
}
return map.get(head);
}
}
总结
暂时没有总结,待续。。。