当前位置:网站首页>[牛客网刷题 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]
边栏推荐
- 每日一题——替换空格
- 【日常訓練--騰訊精選50】557. 反轉字符串中的單詞 III
- Run menu analysis
- Bluebridge cup internet of things basic graphic tutorial - GPIO output control LD5 on and off
- Sword finger offer 05 Replace spaces
- 關於線性穩壓器的五個設計細節
- STM32 --- configuration of external interrupt
- Five design details of linear regulator
- Shell script
- 猜谜语啦(7)
猜你喜欢

猜谜语啦(2)

UE pixel stream, come to a "diet pill"!

Guess riddles (2)

Digital analog 1: linear programming

L298N module use

图解八道经典指针笔试题

剑指 Offer 09. 用两个栈实现队列

Typical low code apaas manufacturer cases

STM32 single chip microcomputer -- debug in keil5 cannot enter the main function

Example 008: 99 multiplication table
随机推荐
leetcode - 445. 两数相加 II
Sword finger offer 06 Print linked list from end to end
Array integration initialization (C language)
Chapter 18 using work queue manager (1)
STM32---ADC
Affected tree (tree DP)
Bluebridge cup internet of things basic graphic tutorial - GPIO input key control LD5 on and off
Program error record 1:valueerror: invalid literal for int() with base 10: '2.3‘
Five design details of linear regulator
剑指 Offer 05. 替换空格
Guess riddles (4)
暑假第一周
亿学学堂给的证券账户安不安全?哪里可以开户
[three tier architecture and JDBC summary]
319. 灯泡开关
Esphone retrofits old fans
Example 007: copy data from one list to another list.
Yolov4 target detection backbone
Low code platform | apaas platform construction analysis
Various types of questions judged by prime numbers within 100 (C language)