Java实现-带环链表

xiaoxiao2021-02-28  133

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

转载请注明原文地址: https://www.6miu.com/read-26911.html

最新回复(0)