(1)分别统计两个链表的长度;
(2)长表先走差值步后,两个链表同时向后走;
(3)判断是否有地址相同的节点,若有相同则为相交节点,没有则两个链表不相交。
测试代码
public static <T extends Comparable<T>>SingleLink.Entry<T> meetNode(SingleLink<T> link1,SingleLink<T> link2){
//1.统计两个链表的节点个数
int countLink1 = countNode(link1);
int countLink2 = countNode(link2);
SingleLink.Entry<T> p1 = link1.getHeadEntry();
SingleLink.Entry<T> p2 = link2.getHeadEntry();
//2.长表先走差值步
int differenceCount = Math.abs(countLink1-countLink2);
if(countLink1>countLink2){
while(differenceCount > 0){
p1 = p1.getNext();
differenceCount--;
}
}else if(countLink2 > countLink1){
while (differenceCount > 0){
p2 = p2.getNext();
differenceCount--;
}
}
//3.两个同时走,判断是否有地址相同的节点,则为相交节点,
//没有则两个链表不相交
while(p1 != null){
if(p1 == p2){
return p1;
}
p1 = p1.getNext();
p2 = p2.getNext();
}
return null;
}
public static void main(String[] args) {
SingleLink<Integer> singleLink = new SingleLink<Integer>();
singleLink.addTail(1);
singleLink.addTail(2);
singleLink.addTail(3);
singleLink.addTail(4);
singleLink.addTail(5);
singleLink.addTail(6);
singleLink.addTail(7);
singleLink.addTail(8); //1 2 3 4 5 6 7 8
//5.构造相交的链表
SingleLink<Integer> singleLink2 = new SingleLink<>();
singleLink2.addTail(1);
singleLink2.addTail(2);
//链表1走到第四个节点
SingleLink.Entry<Integer> p = singleLink.getHeadEntry();
int n = 3;
while(n > 0){
p = p.getNext();
n--;
}
SingleLink.Entry<Integer> p2 = singleLink2.getTailEntry();
//让链表2的尾巴去链接链表1的第四个节点,构成相交链表
p2.setNext(p);
System.out.println(meetNode(singleLink,singleLink2).getValue());