题目:
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的深拷贝。
思路:
对于本题,主要是先拷贝一个不复制random的链表,同时用一个字典记录每一个节点的拷贝地址,然后再通过key-value设置拷贝链表的random指针。
#!/usr/bin/env python3.6
# _*_coding:utf-8 _*_
# @Time : 2019/10/26 18:11
# @Author : Grey
# Definition for a Node.
class Node:
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
class Solution:
def __init__(self):
self.visitedNode = {}
def copyRandomList(self, head: 'Node') -> 'Node':
if head == None:
return None
head_copy = Node(head.val, None, None)
current_copy = head_copy
self.visitedNode[head] = current_copy
current = head
while current.next:
current = current.next
current_copy.next = Node(current.val, None, None)
current_copy = current_copy.next
self.visitedNode[current] = current_copy
current = head
while current:
if current.random:
self.visitedNode[current].random = self.visitedNode[current.random]
current = current.next
return head_copy
但是题解给出了两种其他思路:
(1)回溯,将题中的链表想象成一个图,同时处理next指针和random指针的拷贝,字典记录的是所有被访问过的节点对应的新节点,若已被访问过,则直接返回
(2)改变维护一个旧节点和新节点对应字典的思路,通过将每个拷贝节点都放在原来对应节点的旁边,新旧节点交错存放,可以不需要额外的字典空间,同时解决找不到random指针对应节点的问题。
题解链接:
链接:https://leetcode-cn.com/problems/copy-list-with-random-pointer/solution/fu-zhi-dai-sui-ji-zhi-zhen-de-lian-biao-by-leetcod/
来源:力扣(LeetCode)