When it is required to add the corresponding elements of specific position in two linked lists, a method to add elements to the linked list, a method to print the elements of the linked list, and a method to add elements to corresponding positions of a linked list are defined. Two lists instances are created and the previously defined method is called on these linked list instances.
Below is a demonstration for the same −
Example
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()
Output
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
Explanation
The ‘Node’ class is created.
Another ‘LinkedList_structure’ class with required attributes is created.
It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’.
A method named ‘add_vals’ is defined, that helps add a value to the stack.
Another method named ‘print_it’ is defined, that helps display the values of the linked list.
Another method named ‘add_linked_list’ is defined, that helps add the corresponding elements of the two linked list.
Two instances of the ‘LinkedList_structure’ are created.
Elements are added to both the linked lists.
The ‘add_linked_list’ method is called on these linked lists.
The output is displayed on the console.