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

来源:互联网 发布:ddos软件 编辑:程序博客网 时间:2024/06/02 13:02
/** * 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) {          // write your code here        if(head==null||head.next==null)           return false;                ListNode  fast=head.next;        ListNode  slow=head;        while(fast!=null){            if(fast == slow)               return true;            if(fast.next==null||fast.next.next==null)                return  false;            fast=fast.next.next;            slow=slow.next;                    }        return  true;    }}


语言:  java

java实现

如果有环,返回True,无环,返回False



阅读全文
0 0
原创粉丝点击