linked-list-cycle

題目描述

 

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

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

 

public class Solution {
    /**
     * linked-list-cycle
     * Given a linked list, determine if it has a cycle in it.
     *
     * Follow up:
     * Can you solve it without using extra space?
     * 利用快慢指針,一個走的快,一個走的慢,如果存在環,快的肯定會追到慢的
     * 
     * */
    public boolean hasCycle(ListNode head) {
        if (head==null||head.next==null) {
            return false;
        }
        ListNode low = head, fast = head;
        while(fast!=null&&fast.next!=null) {
            fast = fast.next.next;
            low = low.next;
            if (fast==low) {
                return true;
            }
        }
        return false;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章