题解 | #复杂链表的复制#
复杂链表的复制
http://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba
# 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
dict = {}
cur = pHead
while cur:
dict[cur] = RandomListNode(cur.label)
cur = cur.next
cur = pHead
while cur:
dict[cur].next = dict.get(cur.next)
dict[cur].random = dict.get(cur.random)
cur = cur.next
return dict[pHead]
# 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
while cur:
tmp = cur.next
cur.next = RandomListNode(cur.label)
cur.next.next = tmp
cur = tmp
cur = pHead
while cur:
if cur.random:
cur.next.random = cur.random.next
cur = cur.next.next
new = pHead.next
while pHead:
tmp = pHead.next
if pHead.next:
pHead.next = pHead.next.next
pHead = tmp
return new