forked from iamAnki/CPP-Programs-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntersectionOfTwoSortedLinkedLists_GFG.cpp
More file actions
107 lines (90 loc) · 1.77 KB
/
IntersectionOfTwoSortedLinkedLists_GFG.cpp
File metadata and controls
107 lines (90 loc) · 1.77 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
//Intersection of two sorted Linked lists
//GFG ACCEPTED
//Linkes Lists
#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;
}
}
Node* findIntersection(Node* head1, Node* head2);
int main()
{
int t;
cin>>t;
while(t--)
{
int n,m;
cin>> n >> m;
Node* head1 = inputList(n);
Node* head2 = inputList(m);
Node* result = findIntersection(head1, head2);
printList(result);
cout<< endl;
}
return 0;
}
Node* findIntersection(Node* head1, Node* head2)
{
Node *t1, *t2, *head3, *t3;
if(t1 == NULL || t2 == NULL)
return head3;
t1 = head1;
t2 = head2;
t3 = head3 = NULL;
while(t1 != NULL && t2 != NULL)
{
if(t1->data == t2->data)
{
Node *newNode = new Node(t1->data);
if(head3 == NULL)
{
t3 = head3 = newNode;
}
else
{
t3->next = newNode;
t3 = newNode;
}
t1 = t1->next;
t2 = t2->next;
}
else if(t1->data < t2->data)
{
t1 = t1->next;
}
else
{
t2 = t2->next;
}
}
return head3;
}