102.Linked List Cycle-带环链表(中等题)

来源:互联网 发布:水电安装预算软件 编辑:程序博客网 时间:2024/05/16 09:37

带环链表

  1. 题目

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

  2. 样例

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

  3. 挑战

    不要使用额外的空间

  4. 题解

如果链表有环,则使用快慢指针遍历,终究会有一个时刻两指针相遇。

/** * 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) {          ListNode low = head;        ListNode fast = head;        while (low!= null && fast!=null)        {            low = low.next;            if (fast.next==null)            {                return false;            }            fast = fast.next.next;            if (low == fast)            {                return true;            }        }        return false;    }}

Last Update 2016.10.6

0 0
原创粉丝点击