链表相交

链表相交

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

image-20230325184541053

思路:两个链表不等长,所以要找出他们的差值cha,让长的链表上的指针先走cha不,之后两个链表上的指针同时行进,如果curA == curB,则返回当前节点

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null) return null;
        int lenA = 1;
        int lenB = 1;
        ListNode a = headA;
        ListNode b = headB;
        while(a.next != null){
            lenA++;
            a = a.next;
        }
        while(b.next != null){
            lenB++;
            b = b.next;
        }
        ListNode curA = headA;
        ListNode curB = headB;
        //长的作为curA
        if(lenA < lenB){
            int tempLen = lenA;
            lenA = lenB;
            lenB = tempLen;
            ListNode tempNode = curA;
            curA = curB;
            curB = tempNode;
        }
        
        int cha = Math.abs(lenA - lenB);
        int i = 0;
        while(cha-->0){
            curA = curA.next;
        }
        //while(curA.next != null){
          while(curA != null) { 
            if(curA == curB){
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        
        return null;
    }
}
posted @ 2023-03-28 17:27  Promefire  阅读(25)  评论(0)    收藏  举报