-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintersectionoftwolinkedlist.cpp
More file actions
125 lines (109 loc) · 2.16 KB
/
intersectionoftwolinkedlist.cpp
File metadata and controls
125 lines (109 loc) · 2.16 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
113
114
115
116
117
118
119
120
121
122
123
124
125
// two linked lists merge at one particular point. Print the node
// L1 : 1 -> 2 ->3 -> 4
// L2 : 10 -> 20 -> 3 (L1)
#include <iostream>
#include <stack>
using namespace std;
struct node
{
int data;
node *link;
} * p, *q;
class linkedlist
{
public:
linkedlist()
{
p = NULL;
}
void append(int num)
{
node *temp = new node;
temp->data = num;
temp->link = NULL;
if (p == NULL)
p = temp;
else
{
node *r = p;
while (r->link != NULL)
r = r->link;
r->link = temp;
}
}
void intersect(node *temp)
{
node *r = p;
for (int i = 0; i < 3; i++)
r = r->link;
while (temp->link != NULL)
temp = temp->link;
temp->link = r;
}
void disp(node *a)
{
node *temp = a;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->link;
}
cout << endl;
}
void get_intersection()
{
stack<node *> l1, l2;
node *temp = p;
while (temp != NULL)
{
l1.push(temp);
temp = temp->link;
}
temp = q;
while (temp != NULL)
{
l2.push(temp);
temp = temp->link;
}
if ((l1.top() != l2.top()))
{
cout << "Lists are not merged " << endl;
return;
}
node *r;
while ((!l1.empty()) && (!l2.empty()))
{
if (l1.top() == l2.top())
{
r = l1.top();
l1.pop();
l2.pop();
}
else
{
cout << "Intersection " << r->data << endl;
return;
}
}
}
};
int main()
{
linkedlist l;
l.append(10);
l.append(20);
l.append(30);
l.append(40);
l.append(50);
l.disp(p);
q = new node;
q->data = 5;
q->link = NULL;
node *temp = new node;
temp->data = 7;
temp->link = NULL;
q->link = temp;
l.intersect(q);
l.disp(q);
l.get_intersection();
}