力扣leetcode 160. 相交链表 java

力扣leetcode 160. 相交链表 java_第1张图片

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

你可能感兴趣的:(leetcode)