var copyRandomList = function(head) {if(head == null) return null;let p = head;//第一步,在原链表的每一个节点后创建一个新的节点,值与其相同while(p != null){let newNode = new Node(p.val,null,null);newNode.next = p.next;p.next = newNode;p = newNode.next;}p = head;//第二步,判断原链表节点的random指针是否为空,不为空为每一个新增节点创建与原节点相同的指向while(p != null){if(p.random){p.next.random = p.random.next;}p = p.next.next;}//第三步,拆分新旧节点链表let sentinel = new Node();//哨兵,为空,便于最后返回p = head;sentinel.next = head.next;//指向头结点let curr = sentinel;while(p != null){curr.next = p.next;//从空指向第一个新节点curr = curr.next;//到下一个新节点(即为上面刚指向的节点)p.next = curr.next;//改变就节点的指向,与新节点断开,指向旧结点p = p.next;//到下一个旧节点(即为上面刚指向的节点)}return sentinel.next;
};