当前位置:网站首页>[牛客网刷题 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]
边栏推荐
- Agile project management of project management
- 实例004:这天第几天 输入某年某月某日,判断这一天是这一年的第几天?
- 猜谜语啦(10)
- Explore the authentication mechanism of StarUML
- Program error record 1:valueerror: invalid literal for int() with base 10: '2.3‘
- 暑假第一周
- Business modeling of software model | object modeling
- 猜谜语啦(4)
- Guess riddles (8)
- Sword finger offer 09 Implementing queues with two stacks
猜你喜欢

Various types of questions judged by prime numbers within 100 (C language)

Guess riddles (3)

【三层架构及JDBC总结】

Shift operation of complement

EA introduction notes

STM32 summary (HAL Library) - DHT11 temperature sensor (intelligent safety assisted driving system)

猜谜语啦(2)
Example 001: the number combination has four numbers: 1, 2, 3, 4. How many three digits can be formed that are different from each other and have no duplicate numbers? How many are each?

MHA High available Cluster for MySQL

Example 010: time to show
随机推荐
STM32---IIC
Guess riddles (9)
Esphone Feixun DC1 soft change access homeassstant
Meizu Bluetooth remote control temperature and humidity access homeassistant
Example 010: time to show
Wheel 1:qcustomplot initialization template
轮子1:QCustomPlot初始化模板
猜谜语啦(5)
PIP installation
实例007:copy 将一个列表的数据复制到另一个列表中。
猜谜语啦(8)
如何写Cover Letter?
猜谜语啦(142)
Low code platform | apaas platform construction analysis
How to write cover letter?
Example 002: the bonus paid by the "individual income tax calculation" enterprise is based on the profit commission. When the profit (I) is less than or equal to 100000 yuan, the bonus can be increase
Program error record 1:valueerror: invalid literal for int() with base 10: '2.3‘
Shell script
UE pixel stream, come to a "diet pill"!
Guess riddles (3)