-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintersection_of_2_LL.cpp
More file actions
112 lines (106 loc) · 2.62 KB
/
intersection_of_2_LL.cpp
File metadata and controls
112 lines (106 loc) · 2.62 KB
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
/*
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.
For example, let the first linked list be 1->2->3->4->6 and second linked list be 2->4->6->8, then your function should create and return a third list as 2->4->6.
*/
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int val;
struct Node *next;
};
void push(struct Node **root,int data)
{
Node *newnode=new Node();
struct Node *prev;
prev=*root;
newnode->val=data;
newnode->next=NULL;
if(*root==NULL)
{
*root=newnode;
return;
}
while(prev->next!=NULL)
prev=prev->next;
prev->next=newnode;
}
void print(struct Node *ptr)
{
if(ptr==NULL)
{
cout<<"NO"<<endl;
return;
}
while(ptr!=NULL)
{
cout<<ptr->val<<" ";
ptr=ptr->next;
}
cout<<endl;
}
void intersection(struct Node **head1,struct Node **head2,struct Node **head3);
int main()
{
struct Node *head1=NULL;
struct Node *head2=NULL;
struct Node *head3=NULL;
int t,n1,n2;
cin>>t;
while(t--)
{
struct Node *head1=NULL;
struct Node *head2=NULL;
struct Node *head3=NULL;
cin>>n1>>n2;
int k;
for(int i=0;i<n1;i++)
{
cin>>k;
push(&head1,k);
}
for(int i=0;i<n2;i++)
{
cin>>k;
push(&head2,k);
}
intersection(&head1,&head2,&head3);
print(head3);
}
}
/*Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function is mentioned above.*/
/* The structure of the Linked list Node is as follows:
struct Node {
int val;
struct Node* next;
}; */
void intersection(Node **head1, Node **head2,Node **head3){
Node* p1 = *head1;
Node* p2 = *head2;
Node* last = *head3;
while(p1 && p2){
if(p1->val == p2->val){
Node *newNode=new Node;
newNode->val = p1->val;
newNode->next = NULL;
if(last==NULL){
last = newNode;
*head3 = last;
}
else{
last->next = newNode;
last = newNode;
}
p1=p1->next;
p2=p2->next;
}
else if(p1->val < p2->val)
p1 = p1->next;
else{
p2 = p2->next;
}
}
// Your Code Here
}