Python程序添加2个链表对应的定位元素
当需要在两个链表中添加特定位置的对应元素时,有一种向链表添加元素的方法,一种打印链表元素的方法,以及一种将元素添加到链表对应位置的方法列表被定义。创建两个列表实例,并在这些链接列表实例上调用先前定义的方法。
以下是相同的演示-
示例
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 is not None:
print(curr.data)
curr = curr.next
def add_linked_list(my_list_1, my_list_2):
sum_list = LinkedList_structure()
curr_1 = my_list_1.head
curr_2 = my_list_2.head
while (curr_1 and curr_2):
sum_val = curr_1.data + curr_2.data
sum_list.add_vals(sum_val)
curr_1 = curr_1.next
curr_2 = curr_2.next
if curr_1 is None:
while curr_2:
sum_list.add_vals(curr_2.data)
curr_2 = curr_2.next
else:
while curr_1:
sum_list.add_vals(curr_1.data)
curr_1 = curr_1.next
return sum_list
my_list_1 = LinkedList_structure()
my_list_2 = LinkedList_structure()
my_list = input('Enter the elements of the first linked list : ').split()
for elem in my_list:
my_list_1.add_vals(int(elem))
my_list = input('Enter the elements of the second linked list : ').split()
for elem in my_list:
my_list_2.add_vals(int(elem))
sum_list = add_linked_list(my_list_1, my_list_2)
print('The sum of elements in the linked list is ')
sum_list.print_it()输出结果Enter the elements of the first linked list : 56 34 78 99 54 11 Enter the elements of the second linked list : 23 56 99 0 122 344 The sum of elements in the linked list is 79 90 177 99 176 355
解释
创建了“节点”类。
创建了另一个具有所需属性的“LinkedList_structure”类。
它有一个'init'函数,用于初始化第一个元素,i.e即'head'为'None'。
定义了一个名为“add_vals”的方法,它有助于向堆栈添加一个值。
定义了另一个名为“print_it”的方法,它有助于显示链表的值。
定义了另一个名为“add_linked_list”的方法,它有助于将两个链表的相应元素相加。
创建了“LinkedList_structure”的两个实例。
元素被添加到两个链表中。
'add_linked_list'方法在这些链表上被调用。
输出显示在控制台上。