无需递归查找链表长度的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 calculate_length(self):
curr = self.head
length_val = 0
while curr:
length_val = length_val + 1
curr = curr.next
return length_val
my_instance = my_linked_list()
my_data = input('Enter elements of the linked list ').split()
for elem in my_data:
my_instance.add_value(int(elem))
print('The length of the linked list is ' + str(my_instance.calculate_length()))输出
Enter elements of the linked list 34 12 56 86 32 99 0 6 The length of the linked list is 8
解释
创建了“Node”类。
创建了另一个名为“my_linked_list”的类,其中包含所需的属性。
它有一个“init”函数,用于将第一个元素(即“head”)初始化为“None”,并将最后一个节点初始化为“None”。
定义了另一个名为“add_value”的方法,用于向链表添加数据。
定义了另一个名为“calculate_length”的方法,用于查找链表的长度。
创建了“my_linked_list”类的对象。
获取用户输入以获取链表中的元素。
调用方法向其中添加数据。
调用calculate_length方法来查找列表的长度。
此输出显示在控制台上。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP