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):
curr = self.head
while curr:
print(curr.data)
if curr.next is not None:
curr = curr.next.next
else:
break
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 :56 78 43 51 23 89 0 6 The alternate elements in the linked list are : 56 43 23 0
解釋
建立了“節點”類。
建立了另一個具有所需屬性的“my_linked_list”類。
它有一個“init”函式,用於初始化第一個元素,即“head”為“None”和最後一個節點為“None”。
定義了另一個名為“add_value”的方法,用於向連結串列新增資料。
定義了另一個名為“print_it”的方法,用於迭代列表並列印元素。
定義了另一個名為“alternate_nodes”的方法,用於遍歷連結串列。
建立了“my_linked_list”類的物件。
呼叫alternate_nodes方法,查詢交替索引中的元素。
此輸出顯示在控制檯上。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP