-
Notifications
You must be signed in to change notification settings - Fork 5
/
GFG_IntersectionOfTwoLL.cpp
120 lines (98 loc) · 1.78 KB
/
GFG_IntersectionOfTwoLL.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
/*
https://practice.geeksforgeeks.org/problems/intersection-of-two-linked-list/1#
Intersection of Two Linked Lists
*/
// { Driver Code Starts
//
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *next;
Node(int val)
{
data=val;
next=NULL;
}
};
Node* inputList(int size)
{
Node *head, *tail;
int val;
cin>>val;
head = tail = new Node(val);
while(--size)
{
cin>>val;
tail->next = new Node(val);
tail = tail->next;
}
return head;
}
void printList(Node* n)
{
while(n)
{
cout<< n->data << " ";
n = n->next;
}
}
// } 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* h1, Node* h2)
{
unordered_map<int,int> um;
Node* head = new Node(0);
Node* ptr = head, * newptr;
while(h2) //h2 for order
{
um[h2->data]++;
h2 = h2->next;
}
while(h1)
{
if(um.find(h1->data) != um.end())
{
newptr = new Node(h1->data);
ptr -> next = newptr;
ptr = newptr;
}
h1 = h1->next;
}
return head->next;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n,m;
cin>> n;
Node* head1 = inputList(n);
cin>>m;
Node* head2 = inputList(m);
Solution obj;
Node* result = obj.findIntersection(head1, head2);
printList(result);
cout<< endl;
}
return 0;
}
// } Driver Code Ends