使用递归打印链表中交替节点的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):
self.alternate_helper_fun(self.head)
def alternate_helper_fun(self, curr):
if curr is None:
return
print(curr.data, end = ' ')
if curr.next:
self.alternate_helper_fun(curr.next.next)
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 :78 56 34 52 71 96 0 80 The alternate elements in the linked list are : 78 34 71 0
解释
创建了“Node”类。
创建了另一个具有所需属性的“my_linked_list”类。
它有一个“init”函数,用于将第一个元素(即“head”)初始化为“None”,并将最后一个节点初始化为“None”。
定义了另一个名为“add_value”的方法,用于向链表添加数据。
定义了另一个名为“print_it”的方法,用于迭代列表并打印元素。
定义了另一个名为“alternate_nodes”的方法,用于调用辅助函数。
定义了另一个名为“alternate_helper_fun”的辅助函数,用于迭代链表并显示交替索引中的元素。
这是一个递归函数,因此它会反复调用自身。
这用于调用“alternate_nodes”函数,因为正在使用递归。
创建了“my_linked_list”类的对象。
调用alternate_nodes方法来显示交替元素。
此输出显示在控制台上。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP