一种好的方法
原链表为
next:1-2-3
random 1 - 3
现 为next链路上每一个父节点后 复制一个
变为
next 1- 1- 2- 2-3 -3
然后 从第一个原头指针开始
执行cur.next.random = cur.random.next
这是因为复制的话
cur.next即为复制出的cur节点
而cur.next.random应该是cur.random的复制节点 即cur.random.next
这样操作后 链表变为
next 1- 1- 2- 2-3 -3
random
1-3
1-3
此后 需要断开新链表与原链表
即 从第一个复制出的节点cur = head.next 开始
执行cur.next = cur.next.next
cur = cur.next
最后返回head.next
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def __init__(self):
self.hashdict = {}
def copyRandomList(self, head: 'Node') -> 'Node':
if head == None:
return None
cur = head
while cur != None:
node = Node(cur.val)
node.next = cur.next
cur.next = node
cur = node.next
cur = head
while cur != None:
if cur.random != None:
cur.next.random = cur.random.next
cur = cur.next
cur = cur.next
cur = head.next
while cur.next != None:
#cur.next.next != None:
cur.next = cur.next.next
cur = cur.next
return head.next
我的思路
遍历两遍
第一遍 先找复制每一个指针的next
双指针即可
第二遍 再次使用双指针 同步地找到每一个节点的random
具体是
cur指原head cur2指newhead
如果cur的random是None
二者同时向前推进
如果cur的random不是None
构造两个临时双指针start =head start2=newhead
while start != head.random:
start = start.next
start2 = start2.next
此时找到了cur的random即为start指的节点
因为start2和start是同步的 因此start2所指的节点即为cur2的random
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def __init__(self):
self.hashdict = {}
def copyRandomList(self, head: 'Node') -> 'Node':
if head == None:
return None
newhead = Node(head.val)
cur = head
cur2 = newhead
while cur.next != None:
cur2.next = Node(cur.next.val)
cur2 = cur2.next
cur = cur.next
cur2 = newhead
cur = head
while cur != None:
if cur.random != None:
start = head
start2 = newhead
while start != cur.random:
start = start.next
start2 = start2.next
cur2.random = start2
cur = cur.next
cur2 = cur2.next
else:
cur = cur.next
cur2 = cur2.next
return newhead