[算法]如何判断两个链表是否相交

如何判断两个链表是否相交

解题思路:

如果两个链表相交,那么它们一定有着相同的尾结点,因此实现的思路是:分别遍历两个链表,纪录它们的尾结点,如果它们的尾结点相同,那么这两个链表相交,否则不相交。

代码如下:

public class Solution {

    public boolean isIntersect(Node h1,Node h2){
        if(h1 == null || h2 == null){
            return false;
        }
        Node tail1 = h1;
        while (tail1.next != null) {
            tail1 = tail1.next;
        }
        Node tail2 = h2;
        while (tail2.next != null) {
            tail2 = tail2.next;
        }
        return tail1 == tail2;
    }
}

这个算法的时间复杂度是O(length1+length2),length1和length2分别为两个链表的长度。

Github源码地址:

https://github.com/GeniusVJR/Algorithm-and-Data-Structure/tree/master/如何判断两个链表是否相交

你可能感兴趣的:(算法)