快慢指针判断链表成环的问题
package linkedlist;
/**
* Created by lijie35 on 2020-01-20 10:23 AM .
*/
public class FastSlowPoint {
public static void main(String[] args) {
Node h1 = new Node(0);
Node h2 = new Node(1);
Node h3 = new Node(2);
Node h4 = new Node(3);
Node h5 = new Node(4);
h5.next=h4;
h4.next=h5;
// h3.next=h5;
System.out.println(FastSlowPoint.fsp(h1));
}
/**
* 快慢指针判断连表成环
*/
public static boolean fsp(Node node) {
if (node == null || node.next == null)
return false;
//指向头部
Node slow = node;
//指向头部
Node fast = node;
while (true) {
//慢指针走一步
slow = slow.next;
//快指针走两步
fast = fast.next.next;
//如果快指针碰到队尾就不存在环
if (fast == null && fast.next == null) {
return false;
}
//相遇就是环
if (slow == fast) {
return true;
}
}
}
}
下一篇:
自适应辛普森迭代求曲线的长度
