1、题目
剑指offer35:复杂链表的复制
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
2、代码
使用HashMap。
class Solution {
public Node copyRandomList(Node head) {
//原链表为空
if(head == null) return null;
//原链表节点和新链表节点构成的键指对
Map<Node,Node> map = new HashMap<Node,Node>();
//指向原链表当前节点
Node cur = head;
//复制原链表各节点,建立”原节点➡新节点“的Map映射
while (cur != null){
map.put(cur,new Node(cur.val));//map.put()建立两个节点的映射
cur = cur.next;
}
cur = head;
//构建新链表各节点的next和random指向
while (cur != null){
map.get(cur).next = map.get(cur.next);//map.get(key)通过键找相应的值
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
//返回新链表的头节点
return map.get(head);
}
}
3、随笔
3.1、测试代码
public static void main(String[] args) {
//链表节点的值,依次排
int[] value = {7, 13, 11, 10, 1};
//初始化每个节点的val,构建节点
Node head = new Node(value[0]);
Node node2 = new Node(value[1]);
Node node3 = new Node(value[2]);
Node node4 = new Node(value[3]);
Node node5 = new Node(value[4]);
//初始化每个节点的next,构建成单链表
head.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = null;
//初始化每个节点的random,构建成复杂链表
head.random = null;
node2.random = head;
node3.random = node5;
node4.random = node3;
node5.random = head;
//复杂链表的复制,返回新链表的头节点
Node new_head = copyRandomList(head);
//输出新链表的头节点
System.out.println("new_head.val = " + new_head.val);
}