Skip to content

Commit b31d507

Browse files
committed
Added code for comparing Linked list
1 parent 5eaa6e8 commit b31d507

File tree

1 file changed

+112
-0
lines changed

1 file changed

+112
-0
lines changed
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
class SinglyLinkedListNode:
2+
def __init__(self, node_data):
3+
self.data = node_data
4+
self.next = None
5+
6+
7+
class SinglyLinkedList:
8+
def __init__(self):
9+
self.head = None
10+
self.tail = None
11+
12+
def insert_node(self, node_data):
13+
node = SinglyLinkedListNode(node_data)
14+
15+
if not self.head:
16+
self.head = node
17+
else:
18+
self.tail.next = node
19+
20+
self.tail = node
21+
22+
23+
def print_singly_linked_list(node, sep, fptr):
24+
while node:
25+
fptr.write(str(node.data))
26+
27+
node = node.next
28+
29+
if node:
30+
fptr.write(sep)
31+
32+
33+
def printt(headd):
34+
itr = headd
35+
llstr = []
36+
while itr:
37+
llstr.append(itr.data)
38+
itr = itr.next
39+
return llstr
40+
41+
42+
def compare_lists(llist1, llist2):
43+
ll1 = printt(llist1)
44+
ll2 = printt(llist2)
45+
if ll1 == ll2:
46+
return 'Same'
47+
else:
48+
return 'Not Same'
49+
50+
51+
if __name__ == '__main__':
52+
53+
llist1_count = int(input("Number of nodes in LinkedList1: "))
54+
55+
llist1 = SinglyLinkedList()
56+
print("Enter the value to be stored on linkedlist 1: ")
57+
for _ in range(llist1_count):
58+
llist1_item = input()
59+
llist1.insert_node(llist1_item)
60+
61+
print('\n')
62+
llist2_count = int(input("Number of nodes in LinkedList2: "))
63+
64+
llist2 = SinglyLinkedList()
65+
66+
print("Enter the value to be stored on linkedlist 2: ")
67+
for _ in range(llist2_count):
68+
llist2_item = input()
69+
llist2.insert_node(llist2_item)
70+
71+
result = compare_lists(llist1.head, llist2.head)
72+
73+
print('Result:', result)
74+
75+
'''
76+
Explanation 1:
77+
----------------------------------------------
78+
Input format:
79+
80+
Number of nodes in LinkedList1: 2
81+
Enter the value to be stored on linkedlist 1:
82+
1
83+
2
84+
85+
Number of nodes in LinkedList2: 2
86+
Enter the value to be stored on linkedlist 2:
87+
1
88+
2
89+
-------------------------------------------------
90+
Output:
91+
92+
Result: Same
93+
--------------------------------------------------
94+
Explanation 2:
95+
----------------------------------------------
96+
Input format:
97+
98+
Number of nodes in LinkedList1: 2
99+
Enter the value to be stored on linkedlist 1:
100+
1
101+
2
102+
103+
Number of nodes in LinkedList2: 2
104+
Enter the value to be stored on linkedlist 2:
105+
2
106+
1
107+
-------------------------------------------------
108+
Output:
109+
110+
Result: Not Same
111+
--------------------------------------------------
112+
'''

0 commit comments

Comments
 (0)