// 定义一个Node类,表示链表的节点
public static class Node{
int value; // 节点的值
Node next; // 指向下一个节点的引用
Node rand; // 指向随机节点的引用
// 构造函数,用于创建一个新的节点并初始化其值
Node(int data){
value = data;
}
}
// 定义一个方法copyListWithRand1,用于复制带有随机指针的链表
public static Node copyListWithRand1(Node head) {
// 创建一个HashMap,用于存储原链表中节点与新链表中对应节点的映射关系
HashMap<Node , Node> map = new HashMap<Node , Node>();
Node cur = head; // 当前遍历到的原链表节点
// 遍历原链表,将每个节点及其对应的新节点存入map中
while (cur != null){
map.put(cur, new Node(cur.value));
cur = cur.next;
}
// 重置cur为head,重新遍历原链表
cur = head;
// 再次遍历原链表,设置新链表中每个节点的next和rand指针
while (cur!= null){
// 设置新节点的next指针,指向原节点的下一个节点对应的新节点
map.get(cur).next = map.get(cur.next);
// 设置新节点的rand指针,指向原节点的rand节点对应的新节点
map.get(cur).rand = map.get(cur.rand);
cur = cur.next;
}
// 返回新链表的头节点,即原链表头节点对应的新节点
return map.get(head);
}