BiruLyu
8/5/2017 - 1:33 AM

160. Intersection of Two Linked Lists(#anki).java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public int getListNodeLength(ListNode head){
        ListNode p = head;
        int res = 0;
        while(p != null){
            p = p.next;
            res ++;
        }
        return res;
    }
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA = getListNodeLength(headA), lenB = getListNodeLength(headB);
        while(lenA > lenB) {headA = headA.next; lenA--;}
        while(lenB > lenA) {headB = headB.next; lenB--;}
        while(headA != headB) {headA = headA.next; headB = headB.next;}
        return headA;
    }
}