/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ publicclassSolution{ publicbooleanhasCycle(ListNode head){ ListNode fast = head, slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) { returntrue; } } returnfalse; } }
解决方案4(Golang)
哈希表法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funchasCycle(head *ListNode)bool { seen := map[*ListNode]int{} for head != nil { if _, ok := seen[head]; ok { returntrue } seen[head] = 1 head = head.Next } returnfalse }
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funchasCycle(head *ListNode)bool { if head == nil || head.Next == nil { returnfalse } slow, fast := head, head.Next for fast != slow { if fast == nil || fast.Next == nil { returnfalse } slow = slow.Next fast = fast.Next.Next } returntrue }