题目描述
时间限制
C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M 热度指数:495548
本题知识点
链表(相关题目链接)
题目详细信息
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)(题目链接)
解决思路
解决思路
要求是仍然从老节点能直接找到对应的新节点,则方法为把新节点全都缀连在老节点之后。等设置好所有的random之后再拆分两个链表。注意:最后新老链表都要还原否则不通过。
代码实现
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
if not pHead:return None
cur = pHead
#insert new node between origin listnode
while cur:
tmp = RandomListNode(cur.label)
tmp.next = cur.next
cur.next = tmp
cur = tmp.next
cur = pHead
# find the random
while cur:
tmp = cur.next
if cur.random:
tmp.random = cur.random.next
cur = tmp.next
# to two listNode
cur = pHead
res = pHead.next
while cur.next:
tmp = cur.next
cur.next = tmp.next
cur = tmp
return res