劍指 offer複雜鍊錶的複製

2021-10-07 02:25:21 字數 2700 閱讀 8728

輸入乙個複雜鍊錶(每個節點中有節點值,以及兩個指標,乙個指向下乙個節點,另乙個特殊指標random指向乙個隨機節點),請對此鍊錶進行深拷貝,並返回拷貝後的頭結點。(注意,輸出結果中請不要返回引數中的節點引用,否則判題程式會直接返回空)

重點:

思路一:借助copy庫

# -

*- coding:utf-8-

*-# class randomlistnode:

# def __init__(self, x):

# self.label = x

# self.next = none

# self.random = none

import copy

class solution:

# 返回 randomlistnode

def clone

(self, phead)

:# write code here

return copy.

deepcopy

(phead)

思路二:借助列表

# -

*- coding:utf-8-

*-# 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 not phead:

return none

nodelist =

randomnode =

nodepointer = phead

while nodepointer:

tmpnode =

randomlistnode

(nodepointer.label)

nodelist.

(tmpnode)

if nodepointer.random:

tmprandom =

randomlistnode

(nodepointer.random.label)

randomnode.

(tmprandom)

else

: randomnode.

(none)

nodepointer = nodepointer.next

for i in range

(len

(nodelist)-1

):nodelist[i]

.next = nodelist[i+1]

nodelist[i]

.random = randomnode[i]

nodelist[-1

].random = randomnode[-1

] ret = nodelist[0]

return ret

思路三:

# -

*- coding:utf-8-

*-# 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 == none:

return none

res =

randomlistnode(0

) firstnode = res

while phead != none:

temp =

randomlistnode

(phead.label)

res.label = temp.label

if phead.random != none:

res.random =

randomlistnode

(phead.random.label)

else

: res.random = none

if phead.next != none:

res.next =

randomlistnode

(phead.next.label)

else

: res.next = none

res = res.next

phead = phead.next

return firstnode

劍指offer複雜鍊錶複製

題目描述 輸入乙個複雜鍊錶 每個節點中有節點值,以及兩個指標,乙個指向下乙個節點,另乙個特殊指標指向任意乙個節點 返回結果為複製後複雜鍊錶的head。注意,輸出結果中請不要返回引數中的節點引用,否則判題程式會直接返回空 我的 思路比較笨,就是首先構造乙個正常的不大random指標的鍊錶,然後再去遍歷...

劍指offer 複雜鍊錶複製

輸入乙個複雜鍊錶 每個節點中有節點值,以及兩個指標,乙個指向下乙個節點,另乙個特殊指標指向任意乙個節點 返回結果為複製後複雜鍊錶的head。注意,輸出結果中請不要返回引數中的節點引用,否則判題程式會直接返回空 解題思路 1 複製每個節點,如 複製節點a得到a1,將a1插入節點a後面 2 遍歷鍊錶,a...

劍指offer 複雜鍊錶複製

題目描述 輸入乙個複雜鍊錶 每個節點中有節點值,以及兩個指標,乙個指向下乙個節點,另乙個特殊指標指向任意乙個節點 返回結果為複製後複雜鍊錶的head。注意,輸出結果中請不要返回引數中的節點引用,否則判題程式會直接返回空 非遞迴方法 struct randomlistnode randomlistno...