-
Notifications
You must be signed in to change notification settings - Fork 0
/
(LINKEDLIST)checkingintersectionof2linkedlist(method2.cpp)
115 lines (94 loc) · 2.21 KB
/
(LINKEDLIST)checkingintersectionof2linkedlist(method2.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
// CPP program to print intersection of lists
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
class Node {
public:
int data;
Node* next;
};
// A utility function to return intersection node
Node* intersectPoint(Node* head1, Node* head2)
{
// Maintaining two pointers ptr1 and ptr2
// at the head of A and B,
Node* ptr1 = head1;
Node* ptr2 = head2;
// If any one of head is NULL i.e
// no Intersection Point
if (ptr1 == NULL || ptr2 == NULL) {
return NULL;
}
// Traverse through the lists until they
// reach Intersection node
while (ptr1 != ptr2) {
ptr1 = ptr1->next;
ptr2 = ptr2->next;
// If at any node ptr1 meets ptr2, then it is
// intersection node.Return intersection node.
if (ptr1 == ptr2) {
return ptr1;
}
/* Once both of them go through reassigning,
they will be equidistant from the collision point.*/
// When ptr1 reaches the end of a list, then
// reassign it to the head2.
if (ptr1 == NULL) {
ptr1 = head2;
}
// When ptr2 reaches the end of a list, then
// redirect it to the head1.
if (ptr2 == NULL) {
ptr2 = head1;
}
}
return ptr1;
}
// Function to print intersection nodes
// in a given linked list
void print(Node* node)
{
if (node == NULL)
cout << "NULL";
while (node->next != NULL) {
cout << node->data << "->";
node = node->next;
}
cout << node->data;
}
// Driver code
int main()
{
/*
Create two linked lists
1st Linked list is 3->6->9->15->30
2nd Linked list is 10->15->30
15 30 are elements in the intersection list
*/
Node* newNode;
Node* head1 = new Node();
head1->data = 10;
Node* head2 = new Node();
head2->data = 3;
newNode = new Node();
newNode->data = 6;
head2->next = newNode;
newNode = new Node();
newNode->data = 9;
head2->next->next = newNode;
newNode = new Node();
newNode->data = 15;
head1->next = newNode;
head2->next->next->next = newNode;
newNode = new Node();
newNode->data = 30;
head1->next->next = newNode;
head1->next->next->next = NULL;
Node* intersect_node = NULL;
// Find the intersection node of two linked lists
intersect_node = intersectPoint(head1, head2);
cout << "INTERSEPOINT LIST :";
print(intersect_node);
return 0;
// This code is contributed by bolliranadheer
}