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