Skip to content

Instantly share code, notes, and snippets.

@the-fejw
Created January 27, 2015 07:16
Show Gist options
  • Save the-fejw/8a0e2db377038ea0aa38 to your computer and use it in GitHub Desktop.
Save the-fejw/8a0e2db377038ea0aa38 to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
int lenA = 0, lenB = 0;
ListNode pA = headA, pB = headB;
while (pA != null || pB!= null) {
if (pA != null && pB != null) {
lenA++;
lenB++;
pA = pA.next;
pB = pB.next;
} else if (pA != null) {
lenA++;
pA = pA.next;
} else {
lenB++;
pB = pB.next;
}
}
int diff = Math.abs(lenA - lenB);
pA = headA;
pB = headB;
for (int i = 0; i < diff; i++) {
if (lenA >= lenB) {
pA = pA.next;
} else {
pB = pB.next;
}
}
while (pA != null) {
if (pA.equals(pB)) {
return pA;
}
pA = pA.next;
pB = pB.next;
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment