classSolution{ funchasCycle(_head: ListNode?) -> Bool { if head ==nil { returnfalse } var fast = head var slow = head while fast !=nil&& fast?.next !=nil { fast = fast?.next?.next slow = slow?.next if fast === slow { returntrue } } returnfalse } }
classSolution{ funchasCycle(_head: ListNode?) -> Bool { if head ==nil {returnfalse} var fast = head var slow = head while fast !=nil&& fast?.next !=nil { fast = fast?.next?.next slow = slow?.next if fast === slow { returntrue } } returnfalse } }
执行用时:4 ms, 在所有 C++ 提交中击败了99.77%的用户 内存消耗:8 MB, 在所有 C++ 提交中击败了30.61%的用户
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: boolhasCycle(ListNode *head){ if (head == NULL) returnfalse; ListNode *point = head; while (point->next != NULL){ if (point->val == 100001){ returntrue; } point->val = 100001; point = point->next; } returnfalse; } };