不使用递归打印链接列表中的备用节点的 Python 程序
pythonserver side programmingprogramming更新于 2023/12/27 3:25:00
当需要在不使用递归的情况下打印链接列表中的备用节点时,定义了一种向链接列表添加元素的方法、一种显示链接列表元素的方法以及一种获取链接列表备用值的方法。
下面是同样的演示 −
示例
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
解释
创建了 ‘Node’ 类。
创建了另一个具有必需属性的 ‘my_linked_list’ 类。
它有一个 ‘init’ 函数,用于初始化第一个元素,即将 ‘head’ 初始化为 ‘None’,将最后一个节点初始化为 ‘None’。
定义了另一个名为 ‘add_value’ 的方法,用于将数据添加到链接列表中。
定义了另一个名为 ‘print_it’ 的方法,该方法遍历列表并打印元素。
另一个名为 ‘alternate_nodes’ 的方法被定义为用于迭代链接列表。
创建 ‘my_linked_list’ 类的对象。
调用 alternative_nodes 方法,查找替代索引中的元素。
此输出显示在控制台上。