劍指Offer系列35 複雜鍊錶的複製

2021-10-08 21:36:29 字數 1497 閱讀 2629

請實現 copyrandomlist 函式,複製乙個複雜鍊錶。在複雜鍊錶中,每個節點除了有乙個 next 指標指向下乙個節點,還有乙個 random 指標指向鍊錶中的任意節點或者 null。

示例 1:

輸入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]

輸出:[[7,null],[13,0],[11,4],[10,2],[1,0]]

示例 2:

輸入:head = [[1,1],[2,1]]

輸出:[[1,1],[2,1]]

示例 3:

輸入:head = [[3,null],[3,0],[3,null]]

輸出:[[3,null],[3,0],[3,null]]

示例 4:

輸入:head =

輸出:解釋:給定的鍊錶為空(空指標),因此返回 null。

python

"""

# definition for a node.

class node:

def __init__(self, x: int, next: 'node' = none, random: 'node' = none):

self.val = int(x)

self.next = next

self.random = random

"""# 思路:

# 將鍊錶看作圖,採用dfs求解,借助雜湊表以空間換時間

# 複雜度:

# o(n)

class

solution

:def

copyrandomlist

(self, head:

'node')-

>

'node'

:def

dfs(head):if

not head:

return

none

if head in visited:

return visited[head]

copy=node(head.val,

none

,none

)# 建立新結點

visited[head]

=copy # 存入雜湊表

copy.

next

=dfs(head.

next

)# 遞迴拷貝next結點

copy.random=dfs(head.random)

# 遞迴拷貝random結點

return copy

visited=

return dfs(head)

c++
/*

// definition for a node.

class node

};*/

class

solution

node*

dfs(node* head)

};

劍指 Offer35鍊錶 複雜鍊錶的複製

題目 請實現 copyrandomlist 函式,複製乙個複雜鍊錶。在複雜鍊錶中,每個節點除了有乙個 next 指標指向下乙個節點,還有乙個 random 指標指向鍊錶中的任意節點或者 null。示例 輸出 7,null 13,0 11,4 10,2 1,0 分析 要做到在原煉表和新鍊錶之間建立關係...

劍指Offer 35 複雜鍊錶的複製

請實現啊函式complexlistnode clone complexlistnode phead 複製乙個 複雜鍊錶。在複雜鍊錶中除了有乙個m pnext指標指向下乙個節點,還有乙個m psaibling 指標指向鍊錶中的任意節點或者nullptr。節點定義如下 class complexlist...

(劍指offer)35 複雜鍊錶的複製

輸入乙個複雜鍊錶 每個節點中有節點值,以及兩個指標,乙個指向下乙個節點,另乙個特殊指標指向任意乙個節點 返回結果為複製後複雜鍊錶的head。注意,輸出結果中請不要返回引數中的節點引用,否則判題程式會直接返回空 思路 1.先複製鍊錶節點的值放在原來的節點後面,組成乙個新的鍊錶 2.處理複雜指標 安排複...