链表是否有环

链表是否有环

判断给定的链表中是否有环。如果有环则返回true,否则返回false。

你能给出空间复杂度的解法么?

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null) return false;
        ListNode slow = head;
        ListNode fast = head;
        while(fast!=null && fast.next!=null){
            slow = slow.next;       //慢指针每次走一步
            fast = fast.next.next;    //快指针每次走两步
            if(slow == fast)return true;   //有环
        }
        //  否则没环
        return false;
    }
}
posted @ 2021-01-29 11:14  xiaoff  阅读(105)  评论(0编辑  收藏  举报