-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintersect_unsorted.cpp
130 lines (107 loc) · 2.05 KB
/
intersect_unsorted.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
121
122
123
124
125
126
127
128
129
130
//find intersections of two unsorted 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)
{
if(n == 0) return NULL;
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;
}
int Get_length(node *head)
{
int len = 0;
while(head != NULL)
{
head = head->next;
len++;
}
return len;
}
int findintersection(node *head1, node *head2, int n, int m) {
int d = n-m;
node *p1 = head1, *p2 = head2;
//Now we traverse d times in the longer linked list
// to reach the particular node of longer linked list from where
//the distance to common node is equal to the distance
//between first node of shorted list and the common node
while(d > 0){
p1 = p1->next;
d--;
}
while(p1 != NULL && p2 != NULL) {
if(p1 == p2) return p1->data;
p1 = p1->next;
p2 = p2->next;
}
return -1;
}
void display(node *p)
{
while(p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << "\n";
}
int main()
{
int n, m, k;
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 << "Enter no of nodes in common: ";
cin >> k;
node *common = buildLinkedlist(k);
node *temp = first;
while(temp != NULL && temp->next != NULL)
{
temp = temp->next;
}
if(temp != NULL) temp->next = common;
temp = second;
while(temp != NULL && temp->next != NULL)
{
temp = temp->next;
}
if(temp != NULL) temp->next = common;
cout << "first list: ";
display(first);
cout << "second list: ";
display(second);
n = Get_length(first);
m = Get_length(second);
cout << "common linked list starts at : ";
if(n >= m)
{
cout << findintersection(first, second, n, m) << endl;
}
else
{
cout << findintersection(second, first, m, n) << endl;
}
return 0;
}