参考《程序员代码面试指南》。
链表相交问题
判断两个单链表是否相交:
链表可能是有环也可能是无环的。
- 对于每一个链表,判断链表是否有环,如果有环,返回第一个进环节点。
- 两个无环链表是否相交。
- 两个有环链表是否相交。
- 一个有环一个无环一定不相交。
判断链表是否有环
方法1:创建HashSet存储已遍历过的节点,每遍历到一个新节点,就与HashSet中的节点比较。
方法2:快慢指针法
定义两个指针slow,fast,slow每次走1步,fast每次走两步,如果链表有环,两个指针最终一定能碰上。如果fast指针指向了null,链表无环。
如何判断有环节点的入口?
在两个指针相遇时,将fast指针移动到链表头部,slow指针不动,两个指针同时每次只移动一步,再次相遇的点是入环口。
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;
while (n1 != n2) {
n1 = n1.next;
n2