判断链表中是否有环存在

/**

 * Definition for singly-linked list.

 * class ListNode {

 *     int val;

 *     ListNode next;

 *     ListNode(int x) {

 *         val = x;

 *         next = null;

 *     }

 * }

 */

public class Solution {

    public boolean hasCycle(ListNode head) {

        HashSet<ListNode> hashSet = new HashSet<ListNode>();

        ListNode p;

        p=head;

        while(p!=null){

            if(!hashSet.add(p)) return true;

            p=p.next;

        }

 

        return false;

    }

}

相关文章:

  • 2021-09-13
  • 2022-12-23
  • 2022-12-23
  • 2021-10-11
  • 2021-10-06
猜你喜欢
  • 2021-07-16
  • 2021-04-28
  • 2021-08-03
相关资源
相似解决方案