//
// main.cpp
// Intersection Point
//
// Created by Himanshu on 03/10/21.
//
#include <iostream>
using namespace std;
struct node {
int info = 0;
struct node *next;
};
typedef struct node Node;
node* newNode(int data)
{
node* Node = new node();
Node->info = data;
Node->next = NULL;
return(Node);
}
void printLinkedList (Node* head) {
Node *x = head;
while (x != NULL) {
cout<<(x->info)<<" ";
x = x->next;
}
cout<<endl;
}
Node* insertNode (Node *head, Node* x) {
Node *node = head;
while (node->next != NULL) {
node = node->next;
}
x->next = NULL;
node->next = x;
return head;
}
Node* searchNode (Node *head, int k) {
Node* x = head;
while (x != NULL && x->info != k) {
x = x->next;
}
if (x != NULL && x->info == k) {
return x;
} else {
return NULL;
}
}
int findListLength (Node *head) {
int len = 0;
Node *node = head;
while (node != NULL) {
len++;
node = node->next;
}
return len;
}
Node* solve (Node *head1, Node *head2) {
Node *node1 = head1, *node2 = head2;
int len1 = findListLength(head1), len2 = findListLength(head2);
int diff = len1 - len2;
if (len1 < len2) {
node1 = head2;
node2 = head1;
diff = len2 - len1;
}
for (int i=0; i<diff; i++) {
node1 = node1->next;
}
while (node1 != node2) {
node1 = node1->next;
node2 = node2->next;
}
return node1;
}
int main() {
Node *head1 = newNode(1);
Node *head2 = newNode(9);
head1 = insertNode (head1, newNode(2));
head1 = insertNode (head1, newNode(3));
head1 = insertNode (head1, newNode(4));
head1 = insertNode (head1, newNode(8));
head2 = insertNode (head2, newNode(5));
head2 = insertNode (head2, newNode(7));
Node *x = searchNode(head2, 7);
x->next = searchNode(head1, 4);
cout<<"Linked List 1:"<<endl;
printLinkedList(head1);
cout<<"Linked List 2:"<<endl;
printLinkedList(head2);
x = solve(head1, head2);
if (x) {
cout<<"Intersection point is: "<<(x->info)<<endl;
} else {
cout<<"No intersection point found"<<endl;
}
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBJbnRlcnNlY3Rpb24gUG9pbnQKLy8KLy8gIENyZWF0ZWQgYnkgSGltYW5zaHUgb24gMDMvMTAvMjEuCi8vCgoKI2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