https://leetcode-cn.com/problems/linked-list-cycle/
package factory;
import tree.ListNode;
/**
* @Description: 环形链表
* https://leetcode-cn.com/explore/interview/card/top-interview-quesitons-in-2018/265/linked-list/1146/
* @Author: Jaryn
* @Date: 2019/12/9 16:40
*/
public class HasCycle {
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
ListNode node6 = new ListNode(6);
//ListNode node7 = new ListNode(7);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node4);
node4.setNext(node5);
node5.setNext(node6);
node6.setNext(node1);
//node7.setNext(node1);
System.out.println(hasCycle(node1));
}
public static boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(slow.getNext()!=null && fast.getNext()!=null && fast.getNext().getNext()!=null) {
slow = slow.getNext();
fast = fast.getNext().getNext();
if(slow == fast) {
return true;
}
}
return false;
}
}