python實現鍊錶的反轉遞迴 用遞迴法反轉單鏈表

2021-10-19 21:21:14 字數 1638 閱讀 7584

鍊錶是一種遞迴結構,因此將其與函式式一起使用將產生最佳結果。在您的程式中,您已經使用過程樣式和mutable節點實現了乙個鏈結列表,您將隨著時間的推移更改data和{}的值。雖然這可能感覺像是一種直觀的方法,但我想重點關注一種不可變的規則,它將我們從嚴重的狀態複雜性中解放出來。在

首先,我們修復了node建構函式。我們在構建新節點時設定這兩個屬性,因為它們在程式中稍後不會更改-class node:

def __init__ (self, data, next):

self.data = data

self.next = next

那麼linked_list只是由特定約定構造的單個節點:node.data保留節點的資料

node.next是:

另乙個linked_list

或,none,表示列表的結尾

我們從linked_list的建構函式開始-

^$並實現is_empty、head、和–class linked_list:

def add (self, x):

return linked_list (node (x, self))

def __str__ (self):

if self.is_empty:

return "none"

else:

return str (self.head) + " -> " + str (self.tail)

ls = linked_list().add('a').add('b').add('c')

print (ls)

# c -> b -> a -> none

print (ls.length())

# 3請記住,因為我們已經構建了乙個不可變的鍊錶,add是否會改變呼叫它的列表-ls = linked_list().add('a').add('b').add('c')

print (ls)

# c -> b -> a -> none

print (ls.add('d'))

# d -> c -> b -> a -> none

print (ls)

# c -> b -> a -> none

最後,我們可以實現reverse-class linked_list:

def reverse (self):

def loop (ls, acc):

if ls.is_empty:

return acc

else:

return loop (ls.tail, acc.add(ls.head))

return loop (self, linked_list())

ls = linked_list().add('a').add('b').add('c')

print (ls)

# c -> b -> a -> none

print (ls.reverse())

# a -> b -> c -> none

反轉列表不會改變它print (ls)

# c -> b -> a -> none

print (ls.reverse())

# a -> b -> c -> none

print (ls)

# c -> b -> a -> none

鍊錶的反轉 遞迴實現

此處明確了實現的方法,另外非遞迴 迭代 的方法也可行。首先我們需要知道一些基礎知識 即遞迴的相關概念。遞迴 recursion 即函式自己呼叫自己,若問題可以使用遞迴來解決,則必須滿足以下三個條件 1.可以要把解決的乙個問題轉化為乙個新的問題,這個新問題的解決思路與原來相同,只是在有規律的變化 例如...

鍊錶的建立 輸出 非遞迴反轉 遞迴反轉

鍊錶的建立 輸出 非遞迴反轉 遞迴反轉 如下 include include include include include include include include include include include include using namespace std const int m...

日拱一卒 鍊錶 鍊錶反轉(遞迴解法)

上篇我們主要介紹鍊錶反轉的原地反轉解法。除此以外,是否還有其他解法?當然,今天就來看看鍊錶反轉的遞迴解法。遞迴,字面意思,有 遞 也有 歸 拿我們經常聽到的斐波那契數列來說,公式如下 f n f n 1 f n 2 f 1 1,f 2 1 現在比如求解f 5 的值,按照公式,可以展開為f 5 f 4...