题解 | #复杂链表的复制#
复杂链表的复制
https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba
function Clone(pHead)
{
// write code here
if(!pHead){
return null
}
//复制节点值,放到原节点后
let cur = pHead
while(cur){
let curCopy =new RandomListNode(cur.label)
curCopy.next = cur.next
cur.next = curCopy
cur=curCopy.next
}
//构造random
cur = pHead
while(cur){
if(cur.random){
cur.next.random = cur.random.next
}
cur=cur.next.next
}
//拆表
cur = pHead
let newHead = pHead.next
while(cur.next){
tmp = cur.next
cur.next=tmp.next
cur = tmp
}
return newHead
}
{
// write code here
if(!pHead){
return null
}
//复制节点值,放到原节点后
let cur = pHead
while(cur){
let curCopy =new RandomListNode(cur.label)
curCopy.next = cur.next
cur.next = curCopy
cur=curCopy.next
}
//构造random
cur = pHead
while(cur){
if(cur.random){
cur.next.random = cur.random.next
}
cur=cur.next.next
}
//拆表
cur = pHead
let newHead = pHead.next
while(cur.next){
tmp = cur.next
cur.next=tmp.next
cur = tmp
}
return newHead
}