""" # 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 copyRandomList(self, head: 'Node') -> 'Node': ''' 先不管随机节点,随机保存的是地址索引 ''' newHead = Node(x=0) p = newHead cur = head hash_list = [] count_list = [] while cur: t = Node(x=cur.val) hash_list.append(t) # 保存 p.next = t p = t
# 记录索引位置 randomTarget = cur.random new_p = head count = 0 # print(new_p,randomTarget) while new_p != randomTarget: count += 1 new_p = new_p.next count_list.append(count) ''' 或者在这里找到其random对应的节点,在原链表中的位置 ''' cur = cur.next
# 在这里重建随机索引 p = newHead.next # 新的头结点 cur = head # 原头结点
""" # 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 """ classSolution: defcopyRandomList(self, head: 'Node') -> 'Node': ifnot head: return
cur = head # 1. 复制各节点,并构建拼接链表 while cur: temp = Node(cur.val) temp.next = cur.next cur.next = temp cur = temp.next # 2. 构建各新节点的 random 指向 cur = head while cur: if cur.random: cur.next.random = cur.random.next # 这里是因为,原先链表经过复制,每个节点后面都跟了一他的拷贝 cur = cur.next.next # 3. 拆分两链表 cur = res = head.next pre = head
while cur.next: # 先更新下一个节点,这里对应拆分 pre.next = pre.next.next cur.next = cur.next.next pre=pre.next cur = cur.next pre.next = None# 单独处理原链表尾节点 return res # 返回新链表头节点