题目:
最后整理下
在本题中,单链表可能有环,也可能无环。给定两个单链表的有节点head1和head2,这两个链表可能相交,也可能不相交。请实现一个函数,如果两个链表相交,请返回相交的第一个节点;如果不相交,返回null即可。
思路:分别讨论,先判断是否有环,这里普及一个数学问题,用两个指针,一个快指针,一个慢指针同时从单链表头部开始遍历,一快一慢,若无环,肯定快指针先遍历到null,此时单链表无环,若单链表有环,这两个指针肯定在环中相遇,相遇时,让快指针从头head开始遍历,然后放慢速度跟慢指针一样快,两个继续同时向下遍历,直到相遇,此时就是单链表入环节点。
//若单链表有环返回入环节点,否则返回null
public static Node getLoopNode(Node head){
if (head == null || head.next == null || head.next.next == null) {
return null;
}
Node n1=head.next; //slow
Node n2=head.next.next; //fast
while (n1 != n2) {
if (n2.next==null||n2.next.next==null){
return null;
}
n2=n2.next.next;
n1=n1.next;
}
n2=head; //n2 walk again from head
while (n1 != n2) {
n1=n1.next;
n2=n2.next;
}
return n1;
}
再来讨论是否相交,单链表这个字眼一定要理解清楚,即只有一个next,所有两个无环单链表相交只有一种可能,如图(1)。若一个有环一个无环不可能相交,因为只有一个next。两个有环单链表相交只有两种可能,如图(2)
对于两个无环单链表,连个尾指针是否相等,若不相等说明不相交,若相等让长链表先走比短链表长的距离,然后两个链表一起向下遍历,知道连个指针相等,则就是相交点
//两个无环单链表
public static Node noLoop(Node head1,Node head2){
if (head1==null||head2==null){
return null;
}
Node cur1=head1;
Node cur2=head2;
int n=0;
while (cur1.next != null) {
n++;
cur1=cur1.next;
}
while (cur2.next != null) {
n--;
cur2=cur2.next;
}
if (cur1 != cur2) {
return null;
}
cur1 = n > 0 ? head1 : head2;
cur2 = cur1 == head1 ? head2 : head1;
n = Math.abs(n);
while (n != 0) {
n--;
cur1 = cur1.next;
}
while (cur1 != cur2) {
cur1 = cur1.next;
cur2 = cur2.next;
}
return cur1;
}
两个有环单链表相交其实就是两个无环单链表相交的变种,如图(2-1),做法是一样的,那两个有环单链表相交就是让一个单链表从入环节点向下遍历知道遍历到另一个单链表的入环节点,如图(2-2)
//两个有环单链表
public static Node bothLoop(Node head1, Node loop1, Node head2, Node loop2) {
Node cur1 = null;
Node cur2 = null;
if (loop1 == loop2) {
cur1 = head1;
cur2 = head2;
int n = 0;
while (cur1 != loop1) {
n++;
cur1 = cur1.next;
}
while (cur2 != loop2) {
n--;
cur2 = cur2.next;
}
cur1 = n > 0 ? head1 : head2;
cur2 = cur1 == head1 ? head2 : head1;
n = Math.abs(n);
while (n != 0) {
n--;
cur1 = cur1.next;
}
while (cur1 != cur2) {
cur1 = cur1.next;
cur2 = cur2.next;
}
return cur1;
} else {
cur1 = loop1.next;
while (cur1 != loop1) {
if (cur1 == loop2) {
return loop1;
}
cur1 = cur1.next;
}
return null;
}
}
最后整理下
public static Node getIntersectNode(Node head1,Node head2){
if (head1 == null || head2 == null) {
return null;
}
Node loop1=getLoopNode(head1);
Node loop2=getLoopNode(head2);
//两个无环单链表
if (loop1 == null && loop2 == null) {
return noLoop(head1,head2);
}
//两个有环单链表
if (loop1 != null && loop2 != null) {
return bothLoop(head1, loop1, head2, loop2);
}
return null;
}