您的位置:首页 > 其它

linked-list-cycle

2015-07-04 09:01 323 查看


中等 带环链表

48%

通过

给定一个链表,判断它是否有环。

您在真实的面试中是否遇到过这个题?

Yes

样例

给出 -21->10->4->5, tail connects to node index 1,返回 true

挑战

不要使用额外的空间
linked list cycle ii 不求环开始的位置:
/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: True if it has a cycle, or false
     */
    public boolean hasCycle(ListNode head) {  
        if(head == null || head.next == null){
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while(fast != slow){
            if(fast.next == null || fast.next.next == null){
                return false;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        return true;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: