先看段代碼,關於遞歸生成鏈表的問題,先自己判斷會輸出什麼,再看結果
class Node:
def __init__(self):
self.val = None
self.next = None
def ccc(node,x,res):
if res == x:
return
node = Node()
node.val = res
res = res + 1
ccc(node.next,x,res)
x = Node()
ccc(x,6,0)
print x.val
結果輸出爲None,爲什麼呢?明明已經調用了ccc函數,也把頭結點穿進去了,怎麼會這樣呢?原因在於首先執行了x = Node(),我們假設給x分配了001的內存地址,這個內存裏面放的就是Node類的一個實例,接着我們調用了ccc函數,將x傳遞給了ccc函數的參量node,現在node也指向了001的內存地址,到這似乎沒什麼問題,但接下來node = Node()這一步就是問題關鍵所在,現在node不在指向001的內存地址,而是被新分配了一個內存地址002,裏面也存放的是Node類的一個實例,而我們頭結點所指向的內存並不被ccc函數執行,所以001內存裏的數據並沒有因爲ccc的調用而更新。
好了既然知道了問題所在,我們修改下程序後,看下面這段代碼
class Node:
def __init__(self):
self.val = None
self.next = None
def ccc(node,x,res):
if res == x:
return
if res == 0:
node.val = res
res = res + 1
ccc(node,x,res)
else:
node.next = Node()
node.next.val = res
res = res + 1
ccc(node.next,x,res)
s = Node()
ccc(s,6,0)
while s != None:
print s.val
s = s.next
結果輸出爲0,1,2,3,4,5.正確