PythonServer Side ProgrammingProgramming

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

Live Demo

class Node:
def __init__(self, data):
self.data = data
self.next = None

def __init__(self):
self.last_node = None

if self.last_node is None:
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def print_it(self):
while curr is not None:
print(curr.data)
curr = curr.next

while (curr_1 and curr_2):
sum_val = curr_1.data + curr_2.data
curr_1 = curr_1.next
curr_2 = curr_2.next
if curr_1 is None:
while curr_2:
curr_2 = curr_2.next
else:
while curr_1:
curr_1 = curr_1.next
return sum_list

my_list = input('Enter the elements of the first linked list : ').split()
for elem in my_list:

my_list = input('Enter the elements of the second linked list : ').split()
for elem in my_list:

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.