Python Program To Check If Two Linked Lists Are Identical

Python Program To Check If Two Linked Lists Are Identical

To check if two linked lists are identical in Python, you need to compare the elements of the two lists one by one. Two linked lists are considered identical if they have the same number of nodes and corresponding nodes contain the same data. Below is a Python program to demonstrate how to do this:

Step 1: Define a Node Class

First, define a class for the nodes of the linked list. Each node contains some data and a reference to the next node.

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

Step 2: Define a Function to Check Identical Lists

The function will take two linked list heads as arguments and return True if the lists are identical, and False otherwise.

def are_identical(head1, head2): current1 = head1 current2 = head2 while current1 and current2: if current1.data != current2.data: return False current1 = current1.next current2 = current2.next # If both lists are exhausted, they are identical return current1 is None and current2 is None 

Step 3: Create Linked Lists and Test the Function

You can now create linked lists and use the are_identical function to check if they are identical.

# Utility function to create a new Node def create_node(data): return Node(data) # Creating linked lists # List 1: 1->2->3 head1 = create_node(1) head1.next = create_node(2) head1.next.next = create_node(3) # List 2: 1->2->3 head2 = create_node(1) head2.next = create_node(2) head2.next.next = create_node(3) # Check if lists are identical print("The linked lists are identical:" if are_identical(head1, head2) else "The linked lists are not identical") # You can modify one of the lists and test again head2.next.next.data = 4 print("The linked lists are identical:" if are_identical(head1, head2) else "The linked lists are not identical") 

This program will output whether the two linked lists are identical. It iterates through both lists simultaneously and compares the data in each node. The function are_identical returns False as soon as it finds a pair of nodes with different data or if one list is longer than the other.


More Tags

legend binning ngoninit homescreen python-tesseract uninstallation google-docs-api preg-match dbnull translate-animation

More Programming Guides

Other Guides

More Programming Examples