-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathll_intersection.cpp
78 lines (69 loc) · 1.51 KB
/
ll_intersection.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
#include <iostream>
using namespace std;
class Node{
public:
Node(){
next = NULL;
}
int data;
Node* next;
};
Node* ll_intersection(Node* p_node1,Node* p_node2){
Node* p_temp1 = p_node1;
Node* p_temp2 = p_node2;
int len1 = 0 , len2 = 0;
int diff;
while(p_temp1 != NULL || p_temp2 != NULL){
if(p_temp1 != NULL){
len1 += 1;
p_temp1 = p_temp1->next;
}
if(p_temp2 != NULL){
len2 += 1;
p_temp2 = p_temp2->next;
}
}
diff = abs(len2 - len1);
for(int i=0; i<diff; i++){
if(len2 > len1){
p_node2 = p_node2->next;
}
else{
p_node1 = p_node1->next;
}
}
while(p_node2 != NULL){
if(p_node1 == p_node2){
return p_node1;
}
p_node1 = p_node1->next;
p_node2 = p_node2->next;
}
}
int main(){
Node* p_node1 = new Node;
p_node1->data = 5;
p_node1->next = new Node;
p_node1->next->data = 6;
p_node1->next->next = new Node;
p_node1->next->next->data = 7;
p_node1->next->next->next = new Node;
p_node1->next->next->next->data = 8;
p_node1->next->next->next->next = new Node;
p_node1->next->next->next->next->data = 3;
p_node1->next->next->next->next->next = NULL;
Node* p_node2 = new Node;
p_node2->data = 3;
p_node2->next = new Node;
p_node2->next->data = 5;
p_node2->next->next = new Node;
p_node2->next->next->data = 9;
p_node2->next->next->next = new Node;
p_node2->next->next->next->next = p_node1->next->next;
Node* p_node3 = ll_intersection(p_node1,p_node2);
while(p_node3 != NULL){
cout << p_node3->data << endl;
p_node3 = p_node3->next;
}
return 0;
}