-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlec5_5.cpp
More file actions
146 lines (116 loc) Β· 2.78 KB
/
Copy pathlec5_5.cpp
File metadata and controls
146 lines (116 loc) Β· 2.78 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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
//{ Driver Code Starts
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
/* Link list Node */
struct Node {
int data;
struct Node* next;
Node(int x) {
data = x;
next = NULL;
}
};
vector<int> take() {
vector<int> arr;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
return arr;
}
Node* inputList(int size, vector<int> v) {
if (size == 0)
return NULL;
int val = v[0];
Node* head = new Node(val);
Node* tail = head;
for (int i = 0; i < size - 1; i++) {
val = v[i + 1];
tail->next = new Node(val);
tail = tail->next;
}
return head;
}
// } Driver Code Ends
/* Linked List Node
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
}; */
class Solution {
public:
// Function to find intersection point in Y shaped Linked Lists.
int intersectPoint(Node* head1, Node* head2) {
// Your Code Here
Node *curr1 = head1 , *curr2 = head2;
int count1 = 0 , count2 = 0 ;
while(curr1){
count1++;
curr1 =curr1->next;
}
while(curr2){
count2++;
curr2 = curr2->next;
}
//Number of nodes
curr1 = head1 , curr2 = head2;
while( count1>count2){
count1--;
curr1 = curr1->next;
}
while(count1<count2){
count2--;
curr2 = curr2->next;
}
//
while(curr1!=curr2){
curr1 = curr1->next;
curr2 = curr2->next;
}
if(!curr1)
return -1;
return curr1->data;
}
};
//{ Driver Code Starts.
/* Driver program to test above function*/
int main() {
srand(time(0));
int T, n1, n2, n3;
cin >> T;
cin.ignore();
while (T--) {
vector<int> v1 = take();
vector<int> v2 = take();
vector<int> v3 = take();
int n1 = v1.size(), n2 = v2.size(), n3 = v3.size();
Node* head1 = NULL;
Node* head2 = NULL;
Node* common = NULL;
head1 = inputList(n1, v1);
head2 = inputList(n2, v2);
common = inputList(n3, v3);
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;
Solution ob;
cout << ob.intersectPoint(head1, head2) << endl;
}
return 0;
}
// } Driver Code Ends