Python Program to Add Corresponding Positioned Elements of Two Linked Lists

In this python program, we’re addressing the task of adding corresponding positioned elements of two linked lists. Linked lists are widely used data structures, and this program demonstrates how to perform element-wise addition between two linked lists.

Problem Statement

Given two linked lists with the same length, your goal is to create a new linked list where each node’s value is the sum of the values at the corresponding positions in the input linked lists.

Python Program to Add Corresponding Positioned Elements of Two Linked Lists

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

class LinkedList:
    def __init__(self):
        self.head = None
    
    def append(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = new_node
    
    def display(self):
        current = self.head
        while current:
            print(current.data, end=" -> ")
            current = current.next
        print("None")

def add_linked_lists(list1, list2):
    result = LinkedList()
    current1 = list1.head
    current2 = list2.head
    
    while current1 and current2:
        total = current1.data + current2.data
        result.append(total)
        current1 = current1.next
        current2 = current2.next
    
    return result

# Input: Creating two linked lists
linked_list1 = LinkedList()
elements1 = [1, 2, 3, 4]
for element in elements1:
    linked_list1.append(element)

linked_list2 = LinkedList()
elements2 = [5, 6, 7, 8]
for element in elements2:
    linked_list2.append(element)

print("First Linked List:")
linked_list1.display()

print("\nSecond Linked List:")
linked_list2.display()

result_list = add_linked_lists(linked_list1, linked_list2)

print("\nLinked List After Element-Wise Addition:")
result_list.display()

Input / Output

Python Program to Add Corresponding Positioned Elements of Two Linked Lists

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...