使用遞迴列印連結串列中交替節點的Python程式
當需要使用遞迴列印連結串列中交替節點時,需要定義一個向連結串列新增元素的方法、一個顯示連結串列元素的方法以及一個獲取連結串列交替值的方法。另一個輔助函式用於呼叫前面定義的方法來獲取交替值。
以下是相同的演示 -
示例
class Node:
def __init__(self, data):
self.data = data
self.next = None
class my_linked_list:
def __init__(self):
self.head = None
self.last_node = None
def add_value(self, my_data):
if self.last_node is None:
self.head = Node(my_data)
self.last_node = self.head
else:
self.last_node.next = Node(my_data)
self.last_node = self.last_node.next
def print_it(self):
curr = self.head
while curr:
print(curr.data)
curr = curr.next
def alternate_nodes(self):
self.alternate_helper_fun(self.head)
def alternate_helper_fun(self, curr):
if curr is None:
return
print(curr.data, end = ' ')
if curr.next:
self.alternate_helper_fun(curr.next.next)
my_instance = my_linked_list()
my_list = input("Enter the elements of the linked list :").split()
for elem in my_list:
my_instance.add_value(elem)
print("The alternate elements in the linked list are :")
my_instance.alternate_nodes()輸出
Enter the elements of the linked list :78 56 34 52 71 96 0 80 The alternate elements in the linked list are : 78 34 71 0
解釋
建立了“Node”類。
建立了另一個具有所需屬性的“my_linked_list”類。
它有一個“init”函式,用於將第一個元素(即“head”)初始化為“None”,並將最後一個節點初始化為“None”。
定義了另一個名為“add_value”的方法,用於向連結串列新增資料。
定義了另一個名為“print_it”的方法,用於迭代列表並列印元素。
定義了另一個名為“alternate_nodes”的方法,用於呼叫輔助函式。
定義了另一個名為“alternate_helper_fun”的輔助函式,用於迭代連結串列並顯示交替索引中的元素。
這是一個遞迴函式,因此它會反覆呼叫自身。
這用於呼叫“alternate_nodes”函式,因為正在使用遞迴。
建立了“my_linked_list”類的物件。
呼叫alternate_nodes方法來顯示交替元素。
此輸出顯示在控制檯上。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP