题目
在本题中,单链表可能有环,也可能无环。给定两个单链表的头节点 head1和head2,这两个链表可能相交,也可能不相交。请实现一个函数, 如果两个链表相交,请返回相交的第一个节点;如果不相交,返回null 即可。 要求:如果链表1的长度为N,链表2的长度为M,时间复杂度请达到 O(N+M),额外
空间复杂度请达到O(1)
分析:
1、首先判断两个单链表L1,L2是否有环,并返回入环结点
思路是:快慢指针思想,从head开始,快指针一次走两步,慢指针一次走一步,如果快指针走到null,说明无环,否则有环,快慢指针必会在环上相遇,此时快指针回到头结点,慢指针留在原地,二者同时每次走一步,相遇点即是入环结点。若有环,返回L1,L2的入环结点loop1,loop2
2、有三种情况:(1)两个都无环,(2)一有环一无环,(3)两个都有环
情况(1)两个都无环:
如何找到第一个相交点?:分别从L1,L2走到尾结点end,计算各自长度,然后回到头结点,较长的链表先走两表的长度差步,之后两个再一起走,相遇时返回相遇点
情况(2)一有环一无环
这种情况很明显不可能相交,否则就不是单链表了。
情况(3)两个都有环:
相交(1)如何找到第一个相交点:模仿情况(1)无环的做法
相交(2)如何找到第一个相交点:利用第一部返回的loop1,loop2,从loop1开始,每次往下走一步,若能遇到loop2,则属于相交(2)这种情况,那么第一个相交点就是loop1或者loop2(这里我们选择loop1好了)
代码如下
public static class Node {
public int value;
public Node next;
public Node(int data) {
this.value = data;
}
}
public static Node getIntersectNode(Node head1, Node head2) {
if (head1 == null || head2 == null) {
return null;
}
//getLoopNode方法获得入环结点loop1,loop2,
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;//一有环一无环不可能相交,返回null
}
//获取入环结点方法
public static Node getLoopNode(Node head) {
if (head == null || head.next == null || head.next.next == null) {
return null;
}
Node n1 = head.next; // n1 -> slow
Node n2 = head.next.next; // n2 -> 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;
}
//无环时调用noLoop方法
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++;//计算L1长度
cur1 = cur1.next;
}
while (cur2.next != null) {
n--;//此循环之后,n=L1和L2的长度差
cur2 = cur2.next;
}
if (cur1 != cur2) {
return null;
}
cur1 = n > 0 ? head1 : head2;//令cur1为较长的链表的head
cur2 = cur1 == head1 ? head2 : head1;
n = Math.abs(n);//绝对值
while (n != 0) {//较长的链表先走n步
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;
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) {//loop1若遇到loop2,返回loop1
return loop1;
}
cur1 = cur1.next;
}
return null;//否则就是不相交
}
}