21.03.09 LeetCode160. 相交链表

21.03.09 LeetCode160. 相交链表

 

/**
 * 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) {
        //遍历AB,获得长度
        int lenA=0,lenB=0;
        ListNode cur = headA;
        while(cur!=null)
        {
            lenA++;
            cur = cur.next;
        }
        cur = headB;
        while(cur!=null)
        {
            lenB++;
            cur = cur.next;
        }
        //获取AB的长度差
        int cha = Math.abs(lenA-lenB);
        cur = lenA>lenB?headA:headB;
        ListNode c = cur==headA?headB:headA;
        //让长的表先走cha步
        for(int i = 0;i<cha;i++)
            cur = cur.next;
        //再同时往下走
        while(cur!=c && cur!=null && c!=null)
        {
            cur = cur.next;
            c = c.next;
        }
        return cur==null?null:cur;
    }
}

 

上一篇:LeetCode刷题--链表的相交节点


下一篇:0160. Intersection of Two Linked Lists (E)