Created
February 15, 2015 01:32
-
-
Save dmnugent80/c830a1e42c7fce29d1ce to your computer and use it in GitHub Desktop.
Linked List Get Intersection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
ListNode curr1 = headA; | |
ListNode curr2 = headB; | |
if (curr1 == null || curr2 == null) return null; | |
int count1 = 0; | |
int count2 = 0; | |
while (curr1.next != null){ | |
curr1 = curr1.next; | |
count1++; | |
} | |
while (curr2.next != null){ | |
curr2 = curr2.next; | |
count2++; | |
} | |
if (curr1 != curr2){ | |
return null; | |
} | |
if (count1 == count2){ | |
if (count1 == 1) return headA; | |
curr1 = headA; | |
curr2 = headB; | |
if (count1 == 1) return curr1; | |
while (curr1 != curr2){ | |
curr1 = curr1.next; | |
curr2 = curr2.next; | |
} | |
return curr1; | |
} | |
else if (count1 < count2){ | |
curr1 = headA; | |
curr2 = headB; | |
for (int i = 1; i <= count2 - count1; i++){ | |
curr2 = curr2.next; | |
} | |
while (curr1 != curr2){ | |
curr1 = curr1.next; | |
curr2 = curr2.next; | |
} | |
return curr1; | |
} | |
else{ | |
curr1 = headA; | |
curr2 = headB; | |
for (int i = 1; i <= count1 - count2; i++){ | |
curr1 = curr1.next; | |
} | |
while (curr1 != curr2){ | |
curr1 = curr1.next; | |
curr2 = curr2.next; | |
} | |
return curr1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment