Fork me on github

160 相交链表

/**
 * 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) {
        if(headA == null || headB == null){
            return null;
        }

        ListNode p1 = headA;
        ListNode p2 = headB;

        //计算两个链表的长度,让短的链表指针先走
        
        int len1 = 0, len2 = 0;
        while(p1 != null){
            len1 ++;
            p1 = p1.next;
        }
        while(p2 != null){
            len2 ++;
            p2 = p2.next;
        }

        p1 = headA;
        p2 = headB;
        
        if(len1 > len2){
            p1 = moveFirst(p1, len1 - len2);
        }
        if(len1 < len2){
            p2 = moveFirst(p2, len2 - len1);
        }
        
        //现在p1,p2同步了
        
        while(p1 != p2 && p1 != null){
            p1 = p1.next;
            p2 = p2.next;
        }
        
        return p1;
    }
    
    //让长的先走
    public ListNode moveFirst(ListNode p, int len){
        while(len > 0){
            len --;
            p = p.next;
        }
        return p;
    }
}
posted @ 2020-08-26 21:15  zjy4fun  阅读(92)  评论(0编辑  收藏  举报