相交链表

221 阅读1分钟

题目

image.png

方法1

image.png

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode a = headA, b = headB;
        while (a != b) { 
            a = a == null ? headB : a.next; //需要让ab能走到null,否则会无限循环
            b = b == null ? headA : b.next;
            // a = a.next == null ? headB : a.next; // 错误写法
            // b = b.next == null ? headA : b.next;
        }
        return a;
    }
}

方法二

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lengthA = 0;
        int lengthB = 0;
        ListNode A = headA;
        ListNode B = headB;
        while (A != null) {
            A = A.next;
            lengthA++;
        }
        while (B != null) {
            B = B.next;
            lengthB++;
        }
        int diff = lengthA > lengthB ? lengthA - lengthB : lengthB -lengthA;
        boolean flag = lengthA > lengthB ? true : false;
        while (diff > 0) {
            if (flag) {
                headA = headA.next;
            } else {
                headB = headB.next;
            }
            diff--;
        }
        while (headA != headB) {
            headA = headA.next;
            headB = headB.next;
        }
        return headA;
    }
}