每日一题 leetcode160-相交链表

相交链表

https://leetcode-cn.com/problems/intersection-of-two-linked-lists/

思路一 双指针:

(1)首先指针A和指针B分别指向headA和headB,每一步两个指针都向后移动一步,如果A和B指向同一个节点,那么就找到了相交节点。当指针A指向null的时候,下一步指向headB,当指针B指向null的时候,下一步指向headA。
(2)正确性验证:
假设链表headA的私有部分长度为m,headB的私有部分长度为n,公有部分长度为c(如果不相交那么公有部分长度c为0),若m==n,指针A和指针B不用遍历到另外一个链表就会相遇;若m!=n,那么他们在第二圈也会相遇,走过的距离都是m+n+c;如果链表不相交,那么最后都指向null。

代码:

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null){
            return null;
        }
        ListNode pointA = headA;
        ListNode pointB = headB;
        while(pointA != pointB){
            pointA = pointA==null ? headB : pointA.next;
            pointB = pointB==null ? headA : pointB.next;
        }
        return pointA;
    }
}

思路二:哈希表

你可能感兴趣的:(每日一题 leetcode160-相交链表)