Intersection of Two Linked Lists

/* Write a program to find the node at which
* the intersection of two singly linked lists begins.
* This solution runs O(n) time.
*
* Basic idea:
* 1. Traverse the two linked list to find length M and N;
* 2. Get back to the heads, the skip |M - N| nodes on the longer list;
* 3. Now walk through both lists together until you find the common node.
*
* Important notes:
* When submitting to leetcode, the debug info
* System.out.println() should be commented,
* since it is very time consuming!
*/
 
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
 
/* My answer starts here */
ListNode ptrA = headA;
ListNode ptrB = headB;
int lengthA = 0;
int lengthB = 0;
int i;
 
// get the length of list A
while (null != ptrA) {
//System.out.println("ptrA: " + ptrA.val);
lengthA++;
ptrA = ptrA.next;
}
ptrA = headA; // pointer back to the head
 
// get the length of list B
while (null != ptrB) {
//System.out.println("ptrB: " + ptrB.val);
lengthB++;
ptrB = ptrB.next;
}
ptrB = headB; // pointer back to the head
 
// skip the first |M - N| nodes of the longer list
if (lengthA >= lengthB) {
for (i = 0; i < lengthA - lengthB; i++) {
ptrA = ptrA.next;
}
} else {
for (i = 0; i < lengthB - lengthA; i++) {
ptrB = ptrB.next;
}
}
 
// compare one by one of the remaining nodes
while (null != ptrA) {
if (ptrA.val == ptrB.val) {
return ptrA; // find the intersection
}
ptrA = ptrA.next;
ptrB = ptrB.next;
}
return null; // no intersection
 
/* My answer ends here */
}
}

你可能感兴趣的:(LeetCode,java)