当前位置:网站首页>[daiy4] copy of JZ35 complex linked list
[daiy4] copy of JZ35 complex linked list
2022-07-05 08:43:00 【strawberry47】
subject
answer :
Can't understand the topic , Like input and output ??
Oh ! It turns out that each node is followed by a next Pointers and random Pointer oh
idea :
Use one list Store all random node , Then add them to the regular linked list .
however null Nodes cannot be added next 了 , And in the beginning dummy=pHead, Then there will always be random There is ...
Ah! w(゚Д゚)w, So I made a mistake !! The topic is asking for deep copy , It's not about connecting nodes !
Ideas : Build a dictionary ,key It is the present. node Value ,value yes random Value ; Then traverse the dictionary .
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# return 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
Refer to the answer :
The idea is a little similar , It also creates a hash table ,key Is the current node ,value Is the value of the node ;
Then traverse the original linked list again , Original next and random Take it out
class Solution:
# return 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]
边栏推荐
- Halcon Chinese character recognition
- Infix expression evaluation
- Count of C # LINQ source code analysis
- Example 010: time to show
- Sword finger offer 06 Print linked list from end to end
- 2022.7.4-----leetcode.1200
- Illustration of eight classic pointer written test questions
- MPSoC QSPI Flash 升级办法
- TypeScript手把手教程,简单易懂
- RT-Thread内核快速入门,内核实现与应用开发学习随笔记
猜你喜欢
随机推荐
Classification of plastic surgery: short in long long long
Latex improve
Basic number theory -- Euler function
特征工程
Typical low code apaas manufacturer cases
Business modeling of software model | object modeling
Example 005: three numbers sorting input three integers x, y, Z, please output these three numbers from small to large.
RT-Thread内核快速入门,内核实现与应用开发学习随笔记
皮尔森相关系数
Matlab tips (28) fuzzy comprehensive evaluation
Guess riddles (3)
Business modeling | process of software model
猜谜语啦(5)
Dynamic dimensions required for input: input, but no shapes were provided. Automatically overriding
[matlab] matlab reads and writes Excel
Halcon snap, get the area and position of coins
Sword finger offer 06 Print linked list from end to end
2022.7.4-----leetcode. one thousand and two hundred
Cmder of win artifact
【日常训练--腾讯精选50】557. 反转字符串中的单词 III