-
Notifications
You must be signed in to change notification settings - Fork 0
/
intersect_sorted.cpp
97 lines (82 loc) · 1.49 KB
/
intersect_sorted.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
//find intersections of two sorted linked lists
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* next;
node(int x)
{
data = x;
next = NULL;
}
};
node *buildLinkedlist(int n)
{
int x;
cout << "Enter space separated digits: ";
cin >> x;
node *head = new node(x);
node *tail = head;
for(int i = 0; i < n-1; i++)
{
cin >> x;
tail->next = new node(x);
tail = tail->next;
}
return head;
}
node *findintersection(node *first, node *second)
{
node *res = NULL;
node *temp, *prev = NULL;
while(first != NULL && second != NULL)
{
//cout << "first->data = " << first->data << " compared to second->data = " << second->data << endl;
if(first->data == second->data)
{
temp = new node(first->data);
if(res == NULL) res = temp;
else prev->next = temp;
prev = temp;
first = first->next;
second = second->next;
}
else if(first->data < second->data)
{
first = first->next;
}
else
{
second = second->next;
}
}
return res;
}
void display(node *p)
{
while(p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << "\n";
}
int main()
{
int n, m;
cout << "Enter no. of nodes in first: ";
cin >> n;
node *first = buildLinkedlist(n);
cout << "Enter no. of nodes in second: ";
cin >> m;
node *second = buildLinkedlist(m);
cout << "first list: ";
display(first);
cout << "second list: ";
display(second);
node *ans = findintersection(first, second);
cout << "intersection :";
display(ans);
return 0;
}