Leetcode 141: Linked List Cycle

该博客探讨了如何检测链表中是否存在循环,提供了两种方法:一是简单的暴力遍历,通过遍历100000次来判断;二是使用哈希集合,将遍历到的节点存储并检查重复。这两种算法都能有效地解决链表环状结构的问题,并给出了相应的Java代码实现。
摘要由CSDN通过智能技术生成

问题描述:
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.

Constraints:
The number of the nodes in the list is in the range [0, 10^4].
-105 <= Node.val <= 105
pos is -1 or a valid index in the linked-list.
判断链表是否有循环点

暴力算法:
因为最多有100000个点,所以循环100000遍以后还没找到next=null,则证明必有循环。

public class Solution {
    public boolean hasCycle(ListNode head) {
        for (int i=0; i<100000; i++){
            if (head==null) return false;
            head = head.next;
        }
        return true;
    }
}

用hashset
用hashset和具体的val无关,把每个node的指针存放在hashset中,若没遇到同样的指针,则说明未成环,需要加入set,否则遇到相同的地址说明成环。

代码如下:

public class Solution {
    public boolean hasCycle(ListNode head) {
        Set<ListNode> hset = new HashSet<>();
        //if (head==null)  return false;
        while(head!=null){
            if (!hset.contains(head)){
                hset.add(head);
                head=head.next;
            }
            else{
                return true;
            }
        }
        return false;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值