Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 9, 2017 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/33d2cf92830f9172226c2d9ae98894a5 to your computer and use it in GitHub Desktop.
Save InterviewBytes/33d2cf92830f9172226c2d9ae98894a5 to your computer and use it in GitHub Desktop.
Write a program to find the node at which the intersection of two singly linked lists begins.
package com.interviewbytes.linkedlists;
public class IntersectionNode {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int countA = 0;
int countB = 0;
ListNode current = headA;
while (current != null) {
current = current.next;
countA++;
}
current = headB;
while (current != null) {
current = current.next;
countB++;
}
ListNode small;
ListNode large;
int diff;
if (countA > countB) {
large = headA;
small = headB;
diff = countA - countB;
} else {
large = headB;
small = headA;
diff = countB - countA;
}
while (diff > 0) {
large = large.next;
diff--;
}
while (large != null /* && small!=null*/) {
if (large == small) return large;
large = large.next;
small = small.next;
}
return null;
}
}
package com.interviewbytes.linkedlists;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment