链表--链表相交

31 阅读1分钟

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

示例:

image.png

代码:

public class NodeIntersect {
    public Node nodeIntersect(Node headA, Node headB) {
        int lenA = 0;
        Node tmpA = headA;
        while (tmpA != null) {
            lenA++;
            tmpA = tmpA.next;
        }

        int lenB = 0;
        Node tmpB = headB;
        while (tmpB != null) {
            lenB++;
            tmpB = tmpB.next;
        }

        tmpA = headA;
        tmpB = headB;
        if (lenB > lenA) {
            lenA = lenA ^ lenB;
            lenB = lenA ^ lenB;
            lenA = lenA ^ lenB;
            Node tmp = tmpA;
            tmpA = tmpB;
            tmpB = tmp;
        }

        int gap = lenA - lenB;
        while (gap-- > 0) {
            tmpA = tmpA.next;
        }

        while (tmpA != null) {
            if (tmpA == tmpB) {
                return tmpA;
            }
            tmpA = tmpA.next;
            tmpB = tmpB.next;
        }
        return null;
    }
}