題目描述
輸入乙個複雜鍊錶(每個節點中有節點值,以及兩個指標,乙個指向下乙個節點,另乙個特殊指標指向任意乙個節點),返回結果為複製後複雜鍊錶的head。(注意,輸出結果中請不要返回引數中的節點引用,否則判題程式會直接返回空)
python solution:
# -*- 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):
if phead is none:
return none
current = phead
#在原來的結點之後複製每個結點
while current is not none:
newnode = randomlistnode(current.label)
nextnode = current.next
current.next = newnode
newnode.next = nextnode
current = nextnode
current = phead
#重新遍歷鍊錶給隨機指標賦值
while current is not none:
if current.random is not none:
current.next.random = current.random.next
current = current.next.next
#拆分鍊錶,將鍊錶拆分為原鍊錶和複製後的鍊錶
current = phead
newhead = phead.next
while current is not none:
clonenode = current.next
current.next = clonenode.next
if clonenode.next is not none:
clonenode.next = clonenode.next.next
current = current.next
return newhead
鍊錶 複雜鍊錶的複製
問題描述 請實現函式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指標的節點,之後...