package com.company;
import javax.swing.tree.TreeNode;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
public static void main(String[] args) {
ListNode head = new ListNode();
head.val = 2;
ListNode second = new ListNode();
second.val = 3;
head.next = second;
ListNode third = new ListNode();
third.val = 4;
head.next.next = third;
ListNode four = new ListNode();
four.val = 5;
head.next.next.next = four;
ListNode five = new ListNode();
five.val = 6;
head.next.next.next.next = five;
ListNode six = new ListNode();
six.val = 7;
head.next.next.next.next.next = six;
six.next=third;//环形指针
Boolean b=hasCycle(head);
}
public static boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {//注意这里判断fast.next如果为null,则fast就是最后一个节点了。最后一个节点就不能再取 fast.next.next
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
static class ListNode {
private Integer val;
private ListNode next;
}
}