-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList5.cpp
111 lines (95 loc) · 2.12 KB
/
LinkedList5.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
// Intersection Point in Y Shapped Linked Lists
// https://practice.geeksforgeeks.org/problems/intersection-point-in-y-shapped-linked-lists/1/
// { Driver Code Starts
#include <iostream>
#include <stdio.h>
using namespace std;
/* Link list Node */
struct Node
{
int data;
struct Node *next;
Node(int x)
{
data = x;
next = NULL;
}
};
int intersectPoint(struct Node *head1, struct Node *head2);
Node *inputList(int size)
{
if (size == 0)
return NULL;
int val;
cin >> val;
Node *head = new Node(val);
Node *tail = head;
for (int i = 0; i < size - 1; i++)
{
cin >> val;
tail->next = new Node(val);
tail = tail->next;
}
return head;
}
/* Driver program to test above function*/
int main()
{
int T, n1, n2, n3;
cin >> T;
while (T--)
{
cin >> n1 >> n2 >> n3;
Node *head1 = inputList(n1);
Node *head2 = inputList(n2);
Node *common = inputList(n3);
Node *temp = head1;
while (temp != NULL && temp->next != NULL)
temp = temp->next;
if (temp != NULL)
temp->next = common;
temp = head2;
while (temp != NULL && temp->next != NULL)
temp = temp->next;
if (temp != NULL)
temp->next = common;
cout << intersectPoint(head1, head2) << endl;
}
return 0;
}
// } Driver Code Ends
#include <unordered_map>
/* Linked List Node
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
}; */
/* Should return data of intersection point of two linked
lists head1 and head2.
If there is no intersecting point, then return -1. */
int intersectPoint(Node *head1, Node *head2)
{
// Your Code Here
unordered_map<Node *, int> umap;
//traverse on list and store all pointeres;
Node *temp = head1;
while (temp != NULL)
{
umap[temp] = 1;
temp = temp->next;
}
temp = head2;
while (temp != NULL)
{
if (umap[temp])
{
return temp->data;
}
temp = temp->next;
}
return -1;
}