两题是一样的,但一看就知道谁的题目解释更专业,你懂得。
可以在原来的链表中进行操作,但是个人不太喜欢那样,直接用哈希表来做,时间复杂度也差不多。
解析都在代码注释里:
# -*- coding:utf-8 -*-
# class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
new = RandomListNode(0) # 新链表的哨兵
cur = new
head = pHead
dic = {}
while head is not None:
tmp = RandomListNode(head.label)
dic[head] = tmp # {原节点:原节点的label构建的新节点}
head = head.next
while pHead is not None:
if pHead.random is not None:
dic[pHead].random = dic[pHead.random] # 这里必须是深拷贝,不能直接写=pHead.random软拷贝
cur.next = dic[pHead]
pHead = pHead.next
cur = cur.next
return new.next
这里出现了链表的深拷贝和浅拷贝,很重要!
并且数组的key是可以用链表节点的!!并不是只能str类型数据!!