Skip to content

Instantly share code, notes, and snippets.

@tewari2312
Created May 5, 2024 07:25
Show Gist options
  • Select an option

  • Save tewari2312/776ec4145bb91ad6adc98d310aedfa6d to your computer and use it in GitHub Desktop.

Select an option

Save tewari2312/776ec4145bb91ad6adc98d310aedfa6d to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class IntersectingListNode {
public static void main(String[] args) {
ListNode Anode5 = new ListNode(5);
ListNode Anode4_2 = new ListNode(4, Anode5);
ListNode Anode8 = new ListNode(8, Anode4_2);
ListNode Anode1 = new ListNode(1, Anode8);
ListNode Anode4 = new ListNode(4, Anode1);
ListNode Bnode1 = new ListNode(1, Anode8);
ListNode Bnode6 = new ListNode(6, Bnode1);
ListNode Bnode5 = new ListNode(5, Bnode6);
ListNode resultNode = new IntersectingListNode().getIntersectionNode(Anode4, Bnode5);
printNode(resultNode);
}
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode resultNode = null;
Map<Integer, List<ListNode>> elements = new HashMap<>();
while((headA!=null || headB!=null) && resultNode==null){
if(headA!=null){
if(!elements.containsKey(headA.val)){
List<ListNode> nodes = new ArrayList<>();
nodes.add(headA);
elements.put(headA.val, nodes);
}else{
List<ListNode> nodes = elements.get(headA.val);
for (int i = 0; i < nodes.size(); i++) {
if(nodes.get(i) == headA){
resultNode = headA;
break;
}
}
if(resultNode==null)
nodes.add(headA);
}
headA = headA.next;
}
if(headB!=null){
if(!elements.containsKey(headB.val)){
List<ListNode> nodes = new ArrayList<>();
nodes.add(headB);
elements.put(headB.val, nodes);
}else{
List<ListNode> nodes = elements.get(headB.val);
for (int i = 0; i < nodes.size(); i++) {
if(nodes.get(i) == headB){
resultNode = headB;
break;
}
}
if(resultNode==null)
nodes.add(headB);
}
headB = headB.next;
}
}
return resultNode;
}
static void printNode(ListNode node){
if(node==null){
System.out.println("No common node found");
}else{
while(node!=null){
System.out.print(node.val+" ");
node=node.next;
}
}
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
ListNode(int x, ListNode next) {
val = x;
this.next = next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment