linked-list-cycle

来源:互联网 发布:php 数组取最大值 编辑:程序博客网 时间:2024/06/05 07:12

中等 带环链表

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;    }}


0 0
原创粉丝点击