从链表的最后一个打印第 N 个节点的 Python 程序
当需要从链表的末尾打印特定节点时,定义了方法'list_length'和'return_from_end'方法。'list_length'返回链表的长度。
'return_from_end'方法用于返回从链表末尾开始的第n个元素。
以下是相同的演示-
示例
class Node:
def __init__(self, data):
self.data= data
self.next= None
class LinkedList_structure:
def __init__(self):
self.head= None
self.last_node= None
def add_vals(self, data):
ifself.last_nodeis None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
def list_length(my_list):
my_len = 0
curr = my_list.head
while curr:
curr = curr.next
my_len = my_len + 1
return my_len
def return_from_end(my_list, n):
l = list_length(my_list)
curr = my_list.head
for i in range(l - n):
curr = curr.next
return curr.data
my_instance = LinkedList_structure()
my_list = input('Enter the elements of the linked list..').split()
for elem in my_list:
my_instance.add_vals(int(elem))
n = int(input('Enter the value for n.. '))
my_result = return_from_end(my_instance, n)
print('The nth element from the end is: {}'.format(my_result))输出结果Enter the elements of the linked list..45 31 20 87 4 Enter the value for n.. 2 The nth element from the end is: 87
解释
创建了“节点”类。
创建了另一个具有所需属性的“LinkedList_structure”类。
它有一个“init”函数,用于将第一个元素、i.e“head”和“last_node”初始化为“None”。
定义了一个名为“add_vals”的方法,它有助于向堆栈添加一个值。
定义了一个名为“list_length”的方法,它确定链表的长度,并将其作为输出返回。
定义了另一个名为“return_from_end”的方法,它有助于从链表的末尾返回“n”个值。
'LinkedList_structure'的一个实例被创建。
元素被添加到链表中。
元素显示在控制台上。
'return_from_end'方法在这个链表上被调用。
输出显示在控制台上。