1
+ // C++ program to find if a list is present in another list
2
+ #include < bits/stdc++.h>
3
+ using namespace std ;
4
+
5
+ // A Linked List node
6
+ struct Node
7
+ {
8
+ int data; // To store Data
9
+ Node* next;
10
+ };
11
+
12
+ // Returns true if first list is present in second
13
+ // list
14
+ bool findList (Node* first, Node* second)
15
+ {
16
+ Node* ptr1 = first, *ptr2 = second;
17
+
18
+ // To return true if both linked lists are empty
19
+ if (first == NULL && second == NULL )
20
+ return true ;
21
+
22
+ // To return false if one list is empty and other list is not empty
23
+ if ( first == NULL ||
24
+ (first != NULL && second == NULL ))
25
+ return false ;
26
+
27
+ // To traverse the second list one by one
28
+ while (second != NULL )
29
+ {
30
+ // Initialize ptr2 with value of current node of second
31
+ ptr2 = second;
32
+
33
+ // Matching first list with second list
34
+ while (ptr1 != NULL )
35
+ {
36
+ // If second list becomes empty and first not then return false
37
+ if (ptr2 == NULL )
38
+ return false ;
39
+
40
+ // If data part is same, go to next of both lists
41
+ else if (ptr1->data == ptr2->data )
42
+ {
43
+ ptr1 = ptr1->next ;
44
+ ptr2 = ptr2->next ;
45
+ }
46
+ // If not equal then break the loop
47
+ else break ;
48
+ }
49
+
50
+ // Return true if first list gets traversed completely that means it is matched.
51
+ if (ptr1 == NULL )
52
+ return true ;
53
+
54
+ // Initialize ptr1 with first again
55
+ ptr1 = first;
56
+
57
+ // And go to next node of second list
58
+ second = second->next ;
59
+ }
60
+
61
+ return false ;
62
+ }
63
+
64
+ // function to print all nodes of the list
65
+ void printList (Node* node)
66
+ {
67
+ while (node != NULL )
68
+ {
69
+ printf (" %d " , node->data );
70
+ node = node->next ;
71
+ }
72
+ }
73
+
74
+ // Function to add new node to linked lists
75
+ Node *newNode (int key)
76
+ {
77
+ Node *temp = new Node;
78
+ temp-> data= key;
79
+ temp->next = NULL ;
80
+ return temp;
81
+ }
82
+
83
+ /* Driver program to test above functions*/
84
+ int main ()
85
+ {
86
+ /* Let us create two linked lists to test
87
+ the above functions. Created lists shall be
88
+ a: 1->2->3->4
89
+ b: 1->2->1->2->3->4*/
90
+ Node *a = newNode (1 );
91
+ a->next = newNode (2 );
92
+ a->next ->next = newNode (3 );
93
+ a->next ->next ->next = newNode (4 );
94
+
95
+ Node *b = newNode (1 );
96
+ b->next = newNode (2 );
97
+ b->next ->next = newNode (1 );
98
+ b->next ->next ->next = newNode (2 );
99
+ b->next ->next ->next ->next = newNode (3 );
100
+ b->next ->next ->next ->next ->next = newNode (4 );
101
+
102
+ findList (a,b) ? cout << " LIST FOUND" : cout << " LIST NOT FOUND" ;
103
+
104
+ return 0 ;
105
+ }
0 commit comments