Skip to content

Commit 7a28184

Browse files
committed
sublist search
1 parent 6f8f42b commit 7a28184

1 file changed

Lines changed: 76 additions & 0 deletions

File tree

python/searching/sublist-search.py

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# SUBLIST SEARCH
2+
3+
#Checks whether the first list is present in second list or not.
4+
5+
#Taking fisrt node of second list
6+
class Nodes:
7+
def __init__(self, value = 0):
8+
self.value = value
9+
self.next = None
10+
11+
#Returns TRUE if fisrt list is in the second list.
12+
def findList(first,second):
13+
14+
if not first or not second:
15+
return False
16+
17+
if not first and not second:
18+
return True
19+
20+
p1 = first
21+
p2 = second
22+
# Traversing the second LL
23+
# Checking nodes from both lists
24+
while p2:
25+
#Initializing p2 with current node of second LL
26+
p2 = second
27+
#Starting our matching
28+
while p1:
29+
# If second LL become empty and
30+
# first not, return False,
31+
if not p2:
32+
return False
33+
34+
#if nodes match, increase the pointers
35+
#for checking the next nodes
36+
elif p1.value == p2.value:
37+
p1 = p1.next
38+
p2 = p2.next
39+
40+
#If nodes don't match further or the
41+
#p1 is None/empty
42+
else:
43+
break
44+
#Checks
45+
46+
if not p1: #p1 is empty/None
47+
return True #Completely traversed and matched
48+
49+
#If p1 is not empty/None
50+
p1 = first #bringing back to fisrt
51+
second = second.next #increament second node element
52+
return False
53+
54+
#Driver Code
55+
#Enter two linked list
56+
# Example -
57+
#node_a: 1-> 2-> 3-> 4
58+
# node_b: 1->2->1->2->3->4
59+
node_a = Nodes(1)
60+
node_a.next = Nodes(2)
61+
node_a.next.next = Nodes(3)
62+
node_a.next.next.next = Nodes(4)
63+
64+
node_b = Nodes(1)
65+
node_b.next = Nodes(2)
66+
node_b.next.next = Nodes(1)
67+
node_b.next.next.next = Nodes(2)
68+
node_b.next.next.next.next = Nodes(3)
69+
node_b.next.next.next.next.next = Nodes(4)
70+
71+
if findList(node_a, node_b):
72+
print("LIST FOUND")
73+
else:
74+
print("LIST NOT FOUND")
75+
76+
#OUTPUT : LIST FOUND

0 commit comments

Comments
 (0)