# Python Program to Check if Two Lists are Equal

«
»

This is a Python program to check whether two linked lists are the same.

Problem Description

The program creates two linked lists using data items input from the user and checks whether they are the same.

Problem Solution

1. Create a class Node with instance variables data and next.
3. The variable head points to the first element in the linked list while last_node points to the last.
4. Define methods append and display inside the class LinkedList to append data and display the linked list respectively.
5. Define a function is_equal which takes two linked lists as arguments.
6. The function is_equal returns True only if the two linked lists are of the same length and contain the same data items.
7. Create two instances of LinkedList and append data to it.
8. Check whether they are the same.

Program/Source Code

Here is the source code of a Python program to check whether two linked lists are the same. The program output is shown below.

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

def __init__(self):
self.last_node = None

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

def is_equal(llist1, llist2):
while (current1 and current2):
if current1.data != current2.data:
return False
current1 = current1.next
current2 = current2.next
if current1 is None and current2 is None:
return True
else:
return False

data_list = input('Please enter the elements in the first linked list: ').split()
for data in data_list:
llist1.append(int(data))

data_list = input('Please enter the elements in the second linked list: ').split()
for data in data_list:
llist2.append(int(data))

if is_equal(llist1, llist2):
print('The two linked lists are the same.')
else:
print('The two linked list are not the same.', end = '')```
Program Explanation

1. Two instances of LinkedList are created.
2. The user is prompted to enter the data items for the two lists.
3. The function is_equal determines whether the two linked lists are the same.
4. This result is then displayed.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Runtime Test Cases
```Case 1:
Please enter the elements in the first linked list: 5 8 10 12
Please enter the elements in the second linked list: 5 8 10 12
The two linked lists are the same.

Case 2:
Please enter the elements in the first linked list: 12 3 4 5 0
The two linked list are not the same.

Case 3:
Please enter the elements in the second linked list: 2 19 4
The two linked list are not the same.```

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions. 