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):
ifself.last_nodeis 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 is not None:
print(curr.data)
curr = curr.next
def find_index_val(self, my_key):
curr = self.head
index_val = 0
while curr:
ifcurr.data== my_key:
return index_val
curr = curr.next
index_val = index_val + 1
return -1
my_instance = my_linked_list()
my_list = [67, 4, 78, 98, 32, 0, 11, 8]
for data in my_list:
my_instance.add_value(data)
print('The linked list is : ')
my_instance.print_it()
print()
my_key = int(input('What value would you search for? '))
index_val = my_instance.find_index_val(my_key)
if index_val == -1:
print(str(my_key) + ' was not found.')
else:
print('Element was found at index ' + str(index_val) + '.')
n = int(input('How many elements would you wish to add ? '))
for i in range(n):
data = int(input('Enter data : '))
my_instance.add_value(data)
print('The linked list is : ')
my_instance.print_it()输出结果The linked list is : 67 4 78 98 32 0 11 8 What value would you search for? 11 Element was found at index 6. How many elements would you wish to add ? 2 Enter data : 111 Enter data : 56 The linked list is : 67 4 78 98 32 0 11 8 111 56
解释
创建了“节点”类。
创建了另一个具有必需属性的“my_linked_list”类。
它有一个“init”函数,用于初始化第一个元素,i.e“head”为“None”,最后一个节点为“None”。
定义了另一个名为“add_value”的方法,用于向链表添加数据。
定义了另一个名为“print_it”的方法,用于在控制台上显示链表数据。
定义了另一个名为“find_index_val”的方法,可帮助查找用户输入的元素的索引。
创建了“my_linked_list”类的对象。
定义了一个列表。
迭代这个列表,并在其上调用方法来添加数据。
这使用“print_it”方法显示在控制台上。
要求用户输入要搜索的元素。
'find_index_val'方法被调用,输出显示在控制台上。