複雜鍊錶的複製

2021-10-03 00:17:13 字數 2429 閱讀 1556

題目:

輸入乙個複雜鍊錶(每個節點中有節點值,以及兩個指標,乙個指向下乙個節點,另乙個特殊指標指向任意乙個節點),返回結果為複製後複雜鍊錶的head。(注意,輸出結果中請不要返回引數中的節點引用,否則判題程式會直接返回空)

思路一:

雜湊表**:

# class randomlistnode:

# def __init__(self, x):

# self.label = x

# self.next = none

# self.random = none

class

solution

:# 返回 randomlistnode

defclone

(self, phead):if

not phead:

return

none

clonehead = randomlistnode(phead.label)

node = clonehead

randomlist =

randomlist[phead]

= node

while phead.

next

: phead = phead.

next

node.

next

= randomlistnode(phead.label)

node = node.

next

randomlist[phead]

= node

for i in randomlist:

if i.random:

randomlist[i]

.random = randomlist[i.random]

return clonehead

思路二:

複製每個節點後將複製節點放在原節點後,最後再拆分

**:

# class randomlistnode:

# def __init__(self, x):

# self.label = x

# self.next = none

# self.random = none

class

solution

:# 返回 randomlistnode

defclone

(self, phead):if

not phead:

return

none

p = phead

while p:

node = randomlistnode(p.label)

node.

next

= p.

next

p.next

= node

p = node.

next

p = phead

while p:

if p.random:

p.next

.random = p.random.

next

p = p.

next

.next

clonehead = phead.

next

node = phead

while node.

next

: temp = node.

next

node.

next

= node.

next

.next

node = temp

return clonehead

思路三:

不要臉寫法

**:

# class randomlistnode:

# def __init__(self, x):

# self.label = x

# self.next = none

# self.random = none

import copy

class

solution

:# 返回 randomlistnode

defclone

(self, phead)

: clonehead = copy.deepcopy(phead)

return clonehead

鍊錶 複雜鍊錶的複製

問題描述 請實現函式complexlistnode clone complexlistnode phead 複製乙個複雜鍊錶。在複雜鍊錶中,每個結點除了有乙個next指標指向下乙個結點之外,還有乙個random指向鍊錶中的任意結點或者null。結點的定義如下 struct randomlistnod...

複雜鍊錶複製

複雜鍊錶複製的標頭檔案mlist.h ifndef mlist h define mlist h include include includetypedef int datatype typedef struct node node,pnode,plist pnode crealist datat...

複製複雜鍊錶

題目 輸入乙個複雜鍊錶 每個節點中有節點值,以及兩個指標,乙個指向下乙個節點,另乙個特殊指標指向任意乙個節點 返回結果為複製後複雜鍊錶的head。注意,輸出結果中請不要返回引數中的節點引用,否則判題程式會直接返回空 解題思路 首先有三種解法 第一種就是中規中矩的解法,首先複製next指標的節點,之後...