[leetCode]面试题 02.07. 链表相交

在这里插入图片描述

双指针

通过交换指针位置来使指针在循环过程中达到相同的位置

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode pA = headA;
        ListNode pB = headB;
        while (true) {
            if (pA == null && pB == null) return null;
            if (pA == null) {
                pA = headB;
            }
            if (pB == null) {
                pB = headA;
            }
            if (pA == pB) return pB;
            pA = pA.next;
            pB = pB.next;
        }
    }
}
posted @ 2020-10-23 21:45  消灭猕猴桃  阅读(72)  评论(0编辑  收藏  举报