-
Notifications
You must be signed in to change notification settings - Fork 0
/
Intersection_Of_Two_linked_list.cpp
123 lines (106 loc) · 2.53 KB
/
Intersection_Of_Two_linked_list.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
Node(int x)
: data(x)
, next(nullptr) {}
};
void printList(Node* head) {
while (head != nullptr) {
cout << head->data << ' ';
head = head->next;
}
cout << '\n';
}
// } Driver Code Ends
/* structure of list node:
struct Node
{
int data;
Node *next;
Node(int val)
{
data=val;
next=NULL;
}
};
*/
class Solution {
public:
Node* findIntersection(Node* head1, Node* head2) {
Node* p = head2;
Node* q = head1;
Node* head3 = NULL;
Node* tail = NULL;
map<int, int> mpp;
while(p != NULL)
{
mpp[p->data]++;
p = p->next;
}
while(q != NULL)
{
if(mpp.find(q->data) != mpp.end())
{
Node* temp = new Node(q->data);
if(head3 == NULL)
{
head3 = temp;
tail = temp;
}
else
{
tail->next = temp;
tail = temp;
}
}
q = q->next;
}
return head3;
}
};
//{ Driver Code Starts.
// Driver program to test the above functions
int main() {
int T;
cin >> T;
cin.ignore();
while (T--) {
Node *head1 = nullptr, *tail1 = nullptr;
Node *head2 = nullptr, *tail2 = nullptr;
int tmp;
string input1, input2;
getline(cin, input1);
stringstream ss1(input1);
while (ss1 >> tmp) {
Node* new_node = new Node(tmp);
if (!head1) {
head1 = new_node;
tail1 = new_node;
} else {
tail1->next = new_node;
tail1 = new_node;
}
}
getline(cin, input2);
stringstream ss2(input2);
while (ss2 >> tmp) {
Node* new_node = new Node(tmp);
if (!head2) {
head2 = new_node;
tail2 = new_node;
} else {
tail2->next = new_node;
tail2 = new_node;
}
}
Solution obj;
Node* result = obj.findIntersection(head1, head2);
printList(result);
}
return 0;
}
// } Driver Code Ends