-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathIntersection of LL.cpp
More file actions
115 lines (100 loc) · 2.25 KB
/
Copy pathIntersection of LL.cpp
File metadata and controls
115 lines (100 loc) · 2.25 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
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int d)
{
data = d;
next = NULL;
}
};
// This function gets two arguments - the head pointers of the two linked lists
// Return the node which is the intersection point of these linked lists
// It is assured that the two lists intersect
Node *intersectionOfTwoLinkedLists(Node *l1, Node *l2)
{
if (l1 == NULL || l2 == NULL)
return NULL;
Node *a = l1;
Node *b = l2;
while (a != b)
{
a = a == NULL ? l1 : a->next;
b = b == NULL ? l2 : b->next;
}
return a;
}
/*
*
*
* You do not need to refer or modify any code below this.
* Only modify the above function definition.
* Any modications to code below could lead to a 'Wrong Answer' verdict despite above code being correct.
* You do not even need to read or know about the code below.
*
*
*
*/
Node *buildList(unordered_map<int, Node *> &hash)
{
int x;
cin >> x;
Node *head = new Node(x);
Node *current = head;
hash[x] = head;
while (x != -1)
{
cin >> x;
if (x == -1)
break;
Node *n = new Node(x);
hash[x] = n;
current->next = n;
current = n;
}
current->next = NULL;
return head;
}
void printLinkedList(Node *head)
{
while (head != NULL)
{
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
int main()
{
unordered_map<int, Node *> hash;
Node *l1 = buildList(hash);
Node *l2 = NULL;
int x;
cin >> x;
l2 = new Node(x);
Node *temp = l2;
while (x != -1)
{
cin >> x;
if (x == -1)
break;
if (hash.find(x) != hash.end())
{
temp->next = hash[x];
break;
}
Node *n = new Node(x);
temp->next = n;
temp = n;
}
cout << "L1 - ";
printLinkedList(l1);
cout << "L2 - ";
printLinkedList(l2);
Node *intersectionPoint = intersectionOfTwoLinkedLists(l1, l2);
cout << "Intersection at node with data = " << intersectionPoint->data << endl;
return 0;
}