遍历两次+哈希表
function RandomListNode(x){ this.label = x; this.next = null; this.random = null; } function Clone(pHead) { if(!pHead) return null; //构建哈希表,建立原节点到新节点的映射 let hashMap = new Map(); let head = new RandomListNode(pHead.label); hashMap.set(pHead,head); //遍历指针 let cur = head; let pCur = pHead; while(pCur.next){ cur.next = new RandomListNode(pCur.next.label); hashMap.set(pCur.next,cur.next); cur = cur.next; pCur = pCur.next; } //重新遍历 cur = head; pCur = pHead; while(cur){ cur.random = hashMap.get(pCur.random); cur = cur.next; pCur = pCur.next; } return head; } module.exports = { Clone : Clone };