Python 程序:添加两个链表中对应位置的元素
当需要添加两个链表中特定位置的对应元素时,需要定义一个向链表添加元素的方法、一个打印链表元素的方法,以及一个向链表对应位置添加元素的方法。创建两个链表实例,并在这些链表实例上调用之前定义的方法。
下面是相同功能的演示 -
示例
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):
if self.last_node is 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
解释
创建“Node”类。
创建另一个具有所需属性的“LinkedList_structure”类。
它有一个“init”函数,用于初始化第一个元素,即“head”为“None”。
定义一个名为“add_vals”的方法,用于帮助向栈添加值。
定义另一个名为“print_it”的方法,用于帮助显示链表的值。
定义另一个名为“add_linked_list”的方法,用于帮助添加两个链表的对应元素。
创建两个“LinkedList_structure”的实例。
向两个链表添加元素。
在这些链表上调用“add_linked_list”方法。
在控制台上显示输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP