public class LinkedListYShape {
static Node head1, head2;
public static void main(String[]
args) {
Node node1 = new Node(3);
Node node2 = new Node(6);
Node node3 = new Node(9);
Node node4 = new Node(15);
Node node5 = new Node(30);
Node node6 = new Node(10);
node1.setNextNode(node2);
node2.setNextNode(node3);
node3.setNextNode(node4);
node4.setNextNode(node5);
node6.setNextNode(node3);
// Creating first and second Linked List
LinkedListYShape
list = new
LinkedListYShape();
list.head1 = node1;
list.head2 = node6;
// Approach 1-(Using difference of node counts)
System.out.println("Intersection Node is " +
list.getNode());
// Approach 2-(Simply use two loops)
System.out.println("Intersection Node is "+ list._getIntersectionNodeUsingLoop(head1, head2));
}
int getNode() {
int length1 = getCount(head1);
int length2 = getCount(head2);
int diff;
if (length1 > length2) {
diff =
length1 - length2;
return _getIntesectionNode(diff, head1, head2);
} else {
diff =
length2 - length1;
return _getIntesectionNode(diff, head2, head1);
}
}
int _getIntesectionNode(int d, Node node1, Node node2) {
int i;
Node current1 =
node1;
Node current2 =
node2;
for (i = 0; i < d; i++) {
if (current1 == null) {
return -1;
}
current1 =
current1.getNextNode();
}
while (current1 != null && current2 != null) {
if (current1.getData() == current2.getData())
{
return current1.getData();
}
current1 =
current1.getNextNode();
current2 =
current2.getNextNode();
}
return -1;
}
int getCount(Node node) {
Node current =
node;
int count = 0;
while (current != null) {
count++;
current =
current.getNextNode();
}
return count;
}
Node
_getIntersectionNodeUsingLoop(Node head1, Node head2) {
Node
outerNode,innerNode;
int
length1=getCount(head1),length2=getCount(head2);
if (length1 > length2) {
outerNode =
head1; innerNode = head2;
} else {
outerNode =
head2; innerNode = head1;
}
while (outerNode != null) {
while (innerNode != null) {
if (outerNode == innerNode)
return outerNode;
innerNode
= innerNode.getNextNode();
}
innerNode=head2;
outerNode =
outerNode.getNextNode();
}
return innerNode;
}
}
Output:
Intersection Node is 9
Intersection Node is 9
No comments:
Post a Comment