两个单链表相交的一系列问题
题目:
在本题中,单链表可能有环,也可能无环。给定两个单链表的头结点head1和head2,这两个链表可能相交,也可能不相交,请实现一个函数,如果两个链表相交,请返回相交的第一个节点;如果不相交,返回null。
要求:时间复杂度O(N+M),空间复杂度O(1)。
思路:
第一步判断链表有无环
通过哈希表
例如:1->2->3->4->5->3,在便利的过程中,检查1不在哈希表中,将1加入,再检查2,加入,一直到5,加入,再到3,3已经在哈希表中,说明有环,而且3是环的第一个节点。如果遍历到最后为空,说明不存在环。
不通过哈希表
准备一个快指针和一个慢指针,快指针一次走两步,慢指针一次走一步,若快指针为空了,说明一定无环,若快指针和慢指针相遇了,则一定有环。相遇之后,快指针回到头结点,之后快指针也走一步,当快慢指针再次相遇时即为环的第一个节点。这是一个数学证明,可以当作结论,不用去推导。
第二步若两个链表均无环
用map辅助求解
将head1中的所有节点放入map中,然后遍历head2,第一个检查到head2中节点在map中的即为相交的第一个节点。
不用map辅助求解
求出head1的长度,和链表1的最后一个节点,求出head2的长度以及最后一个节点,先看end1和end2是否相等,若不等,则不可能相交,若相等,则相交,链表1和链表2的长度进行比较,计算差值,长度更长的那个链表先走一个差值的长度,之后两个链表一起走,这时一定会一起走到终点,中间若从一个结点开始相等,则该节点为两个链表相交的第一个节点。
一个链表有环,一个链表无环
结论就是不可能相交。
两个有环链表
这时会有三种结构,如下图所示:
我们用head1表示链表1的头节点,loop1表示链表1入环的第一个节点,同理head2和loop2。若loop1=loop2为第二种结构,若loop1不等于loop2,让loop1继续走,若loop1会等于loop2,说明为第三中结构,若loop1转回来了还没遇到loop2为第一种结构。
//主函数
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)
rerturn noLoop(head1, head2);//两个无环链表的相交问题
if(loop1!=null && loop2!=null)
return bothLoop(head1, loop1, head2, loop2);//两个有环链表的相交问题
return null;//一个有环一个无环没有相交节点
}
public static Node getLoopNode(Node head)
{
if(head==null || head.next==null || head.next.next==null)
return null;
Node n1 = head.next;//慢指针
Node n2 = head.next.next;//快指针
while(n1!=n2)
{
if(n2.next==null || n2.next.next==null)
return null;
n2 = n2.next.next;
n1 = n1.next;
}
n2 = head;
while(n1!=n2)
{
n1 = n1.next;
n2 = n2.next;
}
return n1;
}
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!=null)
{
n++;
cur1 = cur1.next;
}
while(cur2!=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;
}
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;
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;
}
}