ภาพรวม
เมื่อต้องการบวกองค์ประกอบที่อยู่ตำแหน่งตรงกันใน 2 Linked List จะนิยามเมธอดเพิ่มองค์ประกอบ แสดงองค์ประกอบ และเมธอดบวกองค์ประกอบตำแหน่งตรงกัน สร้างอินสแตนซ์รายการ 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):
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เพิ่มค่าเข้า Linked List - เมธอด
print_itแสดงค่าของ Linked List - เมธอด
add_linked_listบวกองค์ประกอบที่อยู่ตำแหน่งตรงกันของ 2 Linked List - สร้างอินสแตนซ์ 2 ตัวของ
LinkedList_structure - เพิ่มองค์ประกอบเข้า Linked List ทั้งสอง
- เรียกเมธอด
add_linked_listกับ Linked List ทั้งสอง - แสดงผลลัพธ์บนคอนโซล