您的位置:首页 > 其它

判断两个链表是否相交,如果相交如何找到第一个相交结点。

2017-09-29 08:54 495 查看
判断两个链表是否相交。

思路:如果两个链表相交,那么他们一定有相同的尾节点,分别遍历两个链表,记录他们的尾节点,如果尾节点相同,则两个链表相交,否则不相交。

public boolean isIntersect(Node h1,Node h2){

if(h1==null||h2==null)

return false;

//找到链表1的最后一个结点

Node tail1=h1;

while(tail1.next!=null){

tail1=tail1.next;

}

//找到链表2的最后一个结点

Node tail2=h2;

while(tail2.next!=null){

tail2=tail2.next;

}

if(tail1==tail2)

return true;

else

return false;

}

}

由于需要遍历两个链表,复杂度为O(len1+len2),len1,len2为链表长度。

如果两个链表相交,如何找到相交的第一个结点?

思路:分别计算两个链表的长度len1,len2,假设链表1比较长,首先对链表较长的那个链表遍历len1-len2个结点到结点p,此时结点p与链表2头结点到他们相交的结点的距离相同,在此时同时遍历两个链表,知道遇到相同的结点为止,这个结点就是他们相交的结点。当然,如果不相交,就没有找第一个相交结点的必要了,所以要先判断是否相交。

public boolean isIntersect(Node h1,Node h2){

if(h1==null||h2==null)

return false;

//找到链表1的最后一个结点

Node tail1=h1;

while(tail1.next!=null){

tail1=tail1.next;

}

//找到链表2的最后一个结点

Node tail2=h2;

while(tail2.next!=null){

tail2=tail2.next;

}

if(tail1==tail2)

return true;

else

return false;

}

}

while(true){
Node t1=h1;

Node t2=h2;

//找出较长的链表先遍历

if(len1>len2){

int d=len1-len2;

while(d!=0){

t1=t1.next;

d--;

}

}

else{

int d= len2-len1;

while(d!=0){

t2=t2.next;

d--;

}

}

while(t1!=t2){

t1=t1.next;

t2=t2.next;

}

return t1;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表
相关文章推荐