【LeetCode】8 判断链表是否有环

题目

判断给定的链表中是否有环

扩展:

你能给出不利用额外空间的解法么?

代码:

//快慢指针能相遇说明有环!
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){
            fast=fast.next.next;
            slow=slow.next;
            if(fast==slow)
                return true;
        }
        return false; 
    }
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×