A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list. 这题 是靠http://www.cnblogs.com/zuoyuan/p/3745126.html 的写的,主要思想是在node后面插入当前node 然后 再用tmp从头开始读
tmp.next.random = tmp.random.next
最后再把链表重新拆分成两个。
代码如下:
# Definition for singly-linked list with a random pointer.
# class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution:
# @param head, a RandomListNode
# @return a RandomListNode
def copyRandomList(self, head):
if head==None:
return head
tmp=head
while tmp:
node=RandomListNode(tmp.label)
node.next=tmp.next
tmp.next=node
tmp=tmp.next.next## jump 2 nodes
tmp=head
while tmp:## to make sure all the nodes are covered
if tmp.random:
tmp.next.random=tmp.random.next## this step is most important
tmp=tmp.next.next ## jump 2 nodes
oldh=head
newhead=newh=head.next
while newh.next:
oldh.next=newh.next
oldh=oldh.next
newh.next=oldh.next
newh=newh.next
oldh.next=None
newh.next=None
return newhead