public bool HasCycle1(ListNode head) { //学习思路 //通过使用具不同速度的快、慢两个指针遍历链表,慢指针每次移动一步,而快指针每次移动两步。 //降低复杂度 if (head == null || head.next == null) { return(false); } ListNode slow = head; ListNode fast = head.next; while (slow != fast) { if (fast == null || fast.next == null) { return(false); } slow = slow.next; fast = fast.next.next; } return(true); }
public ListNode(int x) { val = x; next = null; }