当前位置:网站首页>[牛客网刷题 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]
边栏推荐
- Illustration of eight classic pointer written test questions
- MATLAB skills (28) Fuzzy Comprehensive Evaluation
- Chapter 18 using work queue manager (1)
- Speech recognition learning summary
- 【三层架构及JDBC总结】
- Sword finger offer 05 Replace spaces
- 剑指 Offer 05. 替换空格
- Detailed summary of FIO test hard disk performance parameters and examples (with source code)
- 整形的分类:short in long longlong
- 【日常训练--腾讯精选50】557. 反转字符串中的单词 III
猜你喜欢
Various types of questions judged by prime numbers within 100 (C language)
[nas1] (2021cvpr) attentivenas: improving neural architecture search via attentive sampling (unfinished)
Stm32--- systick timer
Example 010: time to show
UE pixel stream, come to a "diet pill"!
猜谜语啦(142)
实例008:九九乘法表
Business modeling of software model | vision
99 multiplication table (C language)
Apaas platform of TOP10 abroad
随机推荐
Daily question - input a date and output the day of the year
Guess riddles (11)
[matlab] matlab reads and writes Excel
Wheel 1:qcustomplot initialization template
Is the security account given by Yixue school safe? Where can I open an account
One question per day - replace spaces
猜谜语啦(4)
The first week of summer vacation
Numpy pit: after the addition of dimension (n, 1) and dimension (n,) array, the dimension becomes (n, n)
剑指 Offer 05. 替换空格
Digital analog 1: linear programming
Google sitemap files for rails Projects - Google sitemap files for rails projects
Example 006: Fibonacci series
TypeScript手把手教程,简单易懂
猜谜语啦(3)
Example 005: three numbers sorting input three integers x, y, Z, please output these three numbers from small to large.
亿学学堂给的证券账户安不安全?哪里可以开户
Agile project management of project management
STM32 single chip microcomputer -- volatile keyword
Guess riddles (9)