LeetCode -- Linked List Cycle

Question:

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

 

Analysis:

思路一:快慢指针法。前面用到过快慢指针寻找链表的中间节点。若快慢指针会相遇,则说明有环;否则快指针遇到null,则说明无环。

 

Answer:(Beats 100% java submission~)

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null)
            return false;
        ListNode fast = head, slow = head;
        while(fast.next != null || fast == null) {
            if(fast.next == null || fast == null || fast.next.next == null)
                return false;
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast)
                return true;
        }
        return false;
    }
}

 

posted @ 2015-09-12 20:42  江湖小妞  阅读(133)  评论(0编辑  收藏  举报