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