160. 相交链表 [简单]

121 阅读1分钟

题目

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

解法

思路

这个题是当前考验的题。数据结构408当年的原题。

代码

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode p1 = headA;
        ListNode p2 = headB;
        int length1 = length(p1);
        int length2 = length(p2);

        if (length1 < length2) {
            ListNode temp = p1;
            p1 = p2;
            p2 = temp;
        }

        int diff = Math.abs(length1 - length2);
        for (int i = 0; i < diff; i++) {
            p1 = p1.next;
        }
        while (p1 != null && p1 != p2) {
            p1 = p1.next;
            p2 = p2.next;
        }
        return p1;
    }

    private int length(ListNode list) {
        ListNode p = list;
        int length = 0;
        while (p != null) {
            length++;
            p = p.next;
        }
        return length;
    }