题解 | #判断链表中是否有环#JAVA/C++/Go/Python
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
JAVA
public class Solution { public boolean hasCycle(ListNode head) { if(head == null) return false; ListNode fast = head; ListNode slow = head; while(fast!=null&&fast.next!=null){ slow = slow.next; fast = fast.next.next; if(slow == fast) return true; } return false; } }C++
class Solution { public: bool hasCycle(ListNode *head) { if(head==NULL) return false; ListNode* fast=head; ListNode* slow=head; while(fast!=NULL&&fast->next!=NULL) { fast=fast->next->next; slow=slow->next; if(fast==slow) return true; } return false; } };Go
func hasCycle( head *ListNode ) bool { // write code here fast := head slow := head for fast != nil && fast.Next != nil{ slow = slow.Next fast = fast.Next.Next if slow == fast{ return true } } return false }Python
class Solution: def hasCycle(self , head ): # write code here slow = head fast = head while(fast is not None and fast.next is not None): slow = slow.next fast = fast.next.next if slow == fast: return True return False