Intersecting linked list OJ (JavaDS)

Leetcode 160. Intersecting Linked List

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null

insert image description here

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    
    
        if(headA==null||headB==null){
    
    
            return null;
        }
        //先假设长链表是A,短链表是B
        ListNode pl=headA;
        ListNode ps=headB;
        int lenA=0;
        ListNode curA=headA;
        //计算两个链表的长度
        while(curA!=null){
    
    
            lenA++;
            curA=curA.next;
        }
        int lenB=0;
        ListNode curB=headB;
        while(curB!=null){
    
    
            lenB++;
            curB=curB.next;
        }
        int len=lenA-lenB;
        //如果B是长链表,A是短链表,则让B先走差值步,然后A,B同时走,直到走到公共节点
        if(len<0){
    
    
            pl=headB;
            ps=headA;
            len=lenB-lenA;
        }
        for(int i=0;i<len;i++){
    
    
            pl=pl.next;
        }
        while(pl!=ps){
    
    
            pl=pl.next;
            ps=ps.next;
        }
        return pl;
    }

Guess you like

Origin blog.csdn.net/qq_63983125/article/details/127160176