1.检测链表是否有环
定义两个指针,快指针一次走两步,慢指针一次走一步,如果两个指针相遇,说明链表存在环
如果快指针走到尾部,则不存在环
2.找出环的入口点
两个指针相遇后,记录下相遇的位置,慢指针继续走,直到再次走到相遇点,可计算出环的大小n
重新定义两个指针,指针1先走n步,指针2开始走,两指针相遇点即为环的入口点
package me.wcy.j2se.datastructure;
/**
* 检测链表是否有环,若有找出环的入口点
*
* @author chenyan.wang
*
*/
public class IsLoop {
public static void main(String[] args) {
ListNode node5 = new ListNode(5);
ListNode node4 = new ListNode(4, node5);
ListNode node3 = new ListNode(3, node4);
ListNode node2 = new ListNode(2, node3);
ListNode head = new ListNode(1, node2);
node5.next = node3;
System.out.println(isLoop(head));
if (isLoop(head)) {
System.out.println("loop port is " + findLoopPort(head).value);
}
}
private static boolean isLoop(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
private static ListNode findLoopPort(ListNode head) {
if (!isLoop(head)) {
return null;
}
ListNode slow = head;
ListNode fast = head;
int loopSize = 1;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
ListNode node = slow.next;
while (node != slow) {
node = node.next;
loopSize++;
}
break;
}
}
ListNode slow2 = head;
ListNode fast2 = head;
for (int i = 0; i < loopSize; i++) {
fast2 = fast2.next;
}
while (slow2 != fast2) {
slow2 = slow2.next;
fast2 = fast2.next;
}
return slow2;
}
}
输出结果:
true
loop port is 3