当前位置:网站首页>[牛客网刷题 Day4] JZ35 复杂链表的复制
[牛客网刷题 Day4] JZ35 复杂链表的复制
2022-07-05 08:39:00 【strawberry47】
题目
解答:
看不懂题目,好像输入和输出一样??
哦!原来是每个节点后面跟了一个next指针和random指针哦
想法:
用一个list存储所有的random节点,再把他们加到常规链表后面。
但是null节点没法加next了,而且一开始dummy=pHead,那就一直有random存在。。。
啊啊w(゚Д゚)w,原来我搞错题意了!!题目是要求深拷贝,并不是把节点串起来呀!
思路:建立一个字典,key是当前node的值,value是random的值;然后遍历这个字典。
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
if pHead is None:
return None
res = RandomListNode(0)
node_dict = dict()
cur = pHead
while cur:
node_dict[cur.label] = cur.random
cur = cur.next
dummy = res
for node,random1 in node_dict.items():
res.next = RandomListNode(node)
res = res.next
res.random = random1
return dummy.next
参考答案:
思路有点类似,也是创建了一个哈希表,key是当前节点,value是节点的值;
然后再遍历一遍原始链表,把原来的next和random都取出来
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if pHead is None:
return None
dict = {
}
cur = pHead
while cur:
dict[cur] = RandomListNode(cur.label)
cur = cur.next
cur = pHead
while cur:
dict[cur].next = dict.get(cur.next)
dict[cur].random = dict.get(cur.random)
cur = cur.next
return dict[pHead]
边栏推荐
- Cmder of win artifact
- Classification of plastic surgery: short in long long long
- Several problems to be considered and solved in the design of multi tenant architecture
- Esphone Feixun DC1 soft change access homeassstant
- Typescript hands-on tutorial, easy to understand
- Guess riddles (3)
- Infected Tree(树形dp)
- Example 005: three numbers sorting input three integers x, y, Z, please output these three numbers from small to large.
- Apaas platform of TOP10 abroad
- Lori remote control commissioning record
猜你喜欢
Guess riddles (142)
Illustration of eight classic pointer written test questions
Explore the authentication mechanism of StarUML
MySQL之MHA高可用集群
MATLAB skills (28) Fuzzy Comprehensive Evaluation
Pytorch entry record
STM32 single chip microcomputer -- volatile keyword
整形的分类:short in long longlong
实例007:copy 将一个列表的数据复制到另一个列表中。
Guess riddles (9)
随机推荐
Apaas platform of TOP10 abroad
Bluebridge cup internet of things basic graphic tutorial - GPIO output control LD5 on and off
leetcode - 445. Add two numbers II
Mathematical modeling: factor analysis
Yolov4 target detection backbone
Lori remote control LEGO motor
How can fresh students write resumes to attract HR and interviewers
Illustration of eight classic pointer written test questions
亿学学堂给的证券账户安不安全?哪里可以开户
2022.7.4-----leetcode.1200
实例008:九九乘法表
UE像素流,来颗“减肥药”吧!
[daily training -- Tencent selected 50] 557 Reverse word III in string
Example 007: copy data from one list to another list.
每日一题——替换空格
猜谜语啦(142)
Cinq détails de conception du régulateur de tension linéaire
Typescript hands-on tutorial, easy to understand
Guess riddles (4)
Sword finger offer 05 Replace spaces