仅反转链表的前 N 个元素的 Python 程序
当需要反转链表中的一组特定元素时,定义了一个名为“reverse_list”的方法。这将遍历列表,并反转特定的元素集。
以下是相同的演示-
示例
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 print_it(self):
curr = self.head
while curr:
print(curr.data)
curr = curr.next
def reverse_list(my_list, n):
if n == 0:
return
before_val = None
curr = my_list.head
if curr is None:
return
after_val = curr.next
for i in range(n):
curr.next= before_val
before_val = curr
curr = after_val
if after_val is None:
break
after_val = after_val.next
my_list.head.next = curr
my_list.head = before_val
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 number of elements you wish to reverse in the list... '))
reverse_list(my_instance, n)
print('The new list is : ')
my_instance.print_it()输出结果Enter the elements of the linked list... 45 67 89 12 345 Enter the number of elements you wish to reverse in the list... 3 The new list is : 89 67 45 12 345
解释
创建了“节点”类。
创建了另一个具有所需属性的“LinkedList_structure”类。
它有一个'init'函数,用于初始化第一个元素,i.e即'head'为'None'。
定义了一个名为“add_vals”的方法,它有助于向堆栈添加一个值。
定义了另一个名为“print_it”的方法,它有助于在控制台上显示链表的值。
定义了另一个名为“reverse_list”的方法,它有助于反转链表的特定元素集。
'LinkedList_structure'的一个实例被创建。
元素被添加到链表中。
元素显示在控制台上。
需要反转的元素数量取自用户。
在此链表上调用“reverse_list”方法。
输出显示在控制台上。