題目描述
輸入乙個複雜鍊錶(每個節點中有節點值,以及兩個指標,乙個指向下乙個節點,另乙個特殊指標指向任意乙個節點),返回結果為複製後複雜鍊錶的head。(注意,輸出結果中請不要返回引數中的節點引用,否則判題程式會直接返回空)
首先想到的肯定是遞迴來求解了:
# -*- coding:utf-8 -*-
class
randomlistnode
:def
__init__
(self, x)
: self.label = x
self.
next
=none
self.random =
none
class
solution
:# 返回 randomlistnode
defclone
(self, phead)
:# write code here
if phead ==
none
:return
none
res = randomlistnode(phead.label)
res.random = phead.random
res.
next
= self.clone(phead.
next
)return res
還一種思路是複製+複製+拆分:
:# 返回 randomlistnode
defclone
(self, phead)
:# write code here
if phead ==
none
:return
none
head = phead
while head:
tmp = head.
next
head.
next
= randomlistnode(head.label)
head.
next
.next
= tmp
head = tmp
head = phead
while head:
copy_node = head.
next
next_head = copy_node.
next
if head.random:
copy_node.random = head.random.
next
head = next_head
head = phead
res = phead.
next
while head:
copy_node = head.
next
next_head = copy_node.
next
head.
next
= next_head
if next_head:
copy_node.
next
= next_head.
next
else
: copy_node.
next
=none
head = next_head
return res
劍指offer 25 複雜鍊錶的複製
輸入乙個複雜鍊錶 每個節點中有節點值,以及兩個指標,乙個指向下乙個節點,另乙個特殊指標指向任意乙個節點 返回結果為複製後複雜鍊錶的head。注意,輸出結果中請不要返回引數中的節點引用,否則判題程式會直接返回空 include include include using namespace std s...
劍指offer 25 複雜鍊錶的複製
輸入乙個複雜鍊錶 每個節點中有節點值,以及兩個指標,乙個指向下乙個節點,另乙個特殊指標指向任意乙個節點 返回結果為複製後複雜鍊錶的head。注意,輸出結果中請不要返回引數中的節點引用,否則判題程式會直接返回空 本題的最簡答的思路就是先實現結點與next指標的複製,然後利用遍歷整個鍊錶尋找每個結點的r...
劍指offer 25 複雜鍊錶的複製
輸入乙個複雜鍊錶 每個節點中有節點值,以及兩個指標,乙個指向下乙個節點,另乙個特殊指標指向任意乙個節點 返回結果為複製後複雜鍊錶的head。注意,輸出結果中請不要返回引數中的節點引用,否則判題程式會直接返回空 1 複製每個節點,如 複製節點a得到a1,將a1插入節點a後面 2 遍歷鍊錶,a1 ran...