当前位置:网站首页>[牛客网刷题 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]
边栏推荐
- Example 006: Fibonacci series
- STM32 single chip microcomputer - external interrupt
- Esphone Feixun DC1 soft change access homeassstant
- Business modeling of software model | overview
- Pytorch entry record
- 猜谜语啦(11)
- 【三层架构】
- [nas1] (2021cvpr) attentivenas: improving neural architecture search via attentive sampling (unfinished)
- Example 009: pause output for one second
- Guess riddles (9)
猜你喜欢

实例002:“个税计算” 企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.

Mathematical modeling: factor analysis

猜谜语啦(11)

【三层架构】

实例010:给人看的时间

TypeScript手把手教程,简单易懂

Low code platform | apaas platform construction analysis

Explore the authentication mechanism of StarUML

Guess riddles (11)

Matlab tips (28) fuzzy comprehensive evaluation
随机推荐
Bluebridge cup internet of things basic graphic tutorial - GPIO output control LD5 on and off
Affected tree (tree DP)
Tips 1: Web video playback code
实例005:三数排序 输入三个整数x,y,z,请把这三个数由小到大输出。
Is the security account given by Yixue school safe? Where can I open an account
Guess riddles (5)
STM32 single chip microcomputer -- debug in keil5 cannot enter the main function
Numpy 小坑:维度 (n, 1) 和 维度 (n, ) 数组相加运算后维度变为 (n, n)
Some pitfalls of win10 network sharing
leetcode - 445. 两数相加 II
猜谜语啦(4)
2022.7.4-----leetcode. one thousand and two hundred
Weidongshan Internet of things learning lesson 1
Run菜单解析
STM32 lights up the 1.8-inch screen under Arduino IDE
实例008:九九乘法表
[noi simulation] juice tree (tree DP)
【三层架构及JDBC总结】
【NOI模拟赛】汁树(树形DP)
[daily training -- Tencent selected 50] 557 Reverse word III in string