如果2个链表相交,一定有相同的尾结点
思路:分别遍历找到尾结点,比较,若相同则相交,否则不相交。如果相交,求出交点
public class XiangJiao {
public static void main(String[] args){
Node p1=new Node(5);
Node p2=new Node(3);
Node p3=new Node(9);
Node p4=new Node(2);
p1.next=p2;
p2.next=p3;
p3.next=p4;
Node q1=new Node(6);
Node q2=new Node(4);
Node q3=new Node(7);
Node q4=new Node(8);
Node q5=new Node(2);
q1.next=q2;
q2.next=q3;
q3.next=q4;
q4.next=q5;
System.out.println(new XiangJiao().isIntersect(p1,q1));
Node n=getMeetNode(p1,q1);
System.out.println(n.data);
}
public boolean isIntersect(Node h1,Node h2){
if(h1==null||h2==null)
return false;
Node t1=h1;
//找链表1的尾结点
while(t1.next!=null)
t1=t1.next;
Node t2=h2;
//找链表2的尾结点
while(t2.next!=null)
t2=t2.next;
return t1.data==t2.data;
}
//判断是否相交,如果相交找出交点
public static Node getMeetNode(Node h1,Node h2){
if(h1==null||h2==null)
return null;
Node t1=h1;
int len1=1;
//找链表1的尾结点
while(t1.next!=null) {
t1 = t1.next;
len1++;
}
Node t2=h2;
int len2=1;
//找链表2的尾结点
while(t2.next!=null) {
t2 = t2.next;
len2++;
}
//如果不相交
if(t1.data!=t2.data){
return null;
}
Node t_1=h1;
Node t_2=h2;
//找出较长的,先遍历
if(len1>len2){
int d=len1-len2;
while (d!=0){
t_1=t_1.next;
d--;
}
}else{
int d=len2-len1;
while (d!=0){
t_2=t_2.next;
d--;
}
}
while(t_1.data!=t_2.data){//同时遍历
t_1=t_1.next;
t_2=t_2.next;
}
return t_1;
}
}