【Leetcode】141. Linked List Cycle

於淼發表於2018-02-20

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

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

Tips:判斷一個連結串列中是否有環。

思路:設定兩個指標,一個快(fast)一個慢(slow),fast指標每次走兩步,slow每次走一步。當兩個指標相遇,即存在環。若連結串列中沒有環,則fast指標先到達null;

public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null)
            return false;
        boolean hasCy = false;
        ListNode fast = head;
        ListNode slow = head;
        while (fast!=null) {
            if(fast.next!=null){
                fast=fast.next;
                if(fast.next!=null){
                    fast=fast.next;
                    slow=slow.next;
                    if (fast == slow) {
                        hasCy = true;
                        break;
                    }
                }else
                    return false;
            }else
                return false;
        }
        return hasCy;
    }

 

相關文章