题解 | #判断链表中是否有环#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





全部评论

相关推荐

07-11 13:16
湖南工学院 Java
坚定的芭乐反对画饼_...:谁也不知道,毕竟现在的互联网和十年前已经完全不同了,谁都无法预测未来
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 12:10
点赞 评论 收藏
分享
仁者伍敌:牛子这些人还会点一个自动回复,boss都不带回复的
点赞 评论 收藏
分享
难怪不开摄像头,全是简单的性格题,比大疆友善多了
NULL10086:今早上发的测评,我这还没做呢,官网上已经显示挂了
投递大疆等公司7个岗位
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务