Skip to content

Commit 660c5f5

Browse files
authored
Merge point of Linked Lists
Create a merge point of two linked lists and print the merge point of linked lists.
1 parent c16162c commit 660c5f5

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Merge point of Linked Lists

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Node: #node creation
2+
def __init__(self,data):
3+
self.data=data
4+
self.next=None
5+
class Llist: #main logic for list
6+
def __init__(self):
7+
self.head=None
8+
def build(self,data):
9+
new_node=Node(data) #calling Node class for creation of new_node
10+
if self.head is None:
11+
self.head=new_node
12+
else:
13+
temp=self.head
14+
while temp.next is not None:
15+
temp=temp.next
16+
temp.next=new_node
17+
#MERGE POINT/INTERSECTION POINT OF LINKED LIST
18+
def get_intersection_node(self,other_list):
19+
a,b=self.head,other_list.head
20+
while a!=b:
21+
a=other_list.head if not a else a.next
22+
#a is none and a.next is none assign to opposite list head
23+
b=self.head if not b else b.next
24+
#b is none and a.next is none assign to opposite list head
25+
return a
26+
def display(self):
27+
temp=self.head
28+
while temp is not None:
29+
print(temp.data,end="->")
30+
temp=temp.next
31+
print("None")
32+
l1=Llist()
33+
l1.build(1)
34+
l1.build(2)
35+
merge_node=Node(3)
36+
l1.head.next.next=merge_node
37+
l1.build(4)
38+
l1.build(5)
39+
l2=Llist()
40+
l2.head=merge_node
41+
l2.build(6)
42+
l2.build(7)
43+
l2.build(8)
44+
print("List 1:")
45+
l1.display()
46+
print("List 2:")
47+
l2.display()
48+
#find and print the merge Point
49+
merge_point=l1.get_intersection_node(l2)
50+
print("Merge Point:",merge_point.data if merge_point else "No merge point")

0 commit comments

Comments
 (0)