/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funchasCycle(head*ListNode)bool{s:=map[*ListNode]bool{}for;head!=nil;head=head.Next{ifs[head]{returntrue}s[head]=true}returnfalse}
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funchasCycle(head*ListNode)bool{slow,fast:=head,headforfast!=nil&&fast.Next!=nil{slow,fast=slow.Next,fast.Next.Nextifslow==fast{returntrue}}returnfalse}
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } *//** * @param {ListNode} head * @return {boolean} */varhasCycle=function(head){letslow=head;letfast=head;while(fast&&fast.next){slow=slow.next;fast=fast.next.next;if(slow===fast){returntrue;}}returnfalse;};
1 2 3 4 5 6 7 8 910111213141516171819202122232425
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { * val = x; * next = null; * } * } */publicclassSolution{publicboolHasCycle(ListNodehead){varfast=head;varslow=head;while(fast!=null&&fast.next!=null){fast=fast.next.next;slow=slow.next;if(fast==slow){returntrue;}}returnfalse;}}