Leetcode--Java--141. Linked List Cycle

题目描述

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.

样例描述

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

思路

  1. 哈希表法:用一个哈希表来存储已经出现过的结点,如果插入失败add方法会返回null就说明存在过,那就是有环
  2. 快慢指针法:设置两个指针,快的是慢的速度的两倍,快的肯定先入环,两个指针最后一定会在某个位置相遇。注意用while循环的话,两个指针初始的位置别相同,否则无法进入循环体。 注意初始要判断head 和head.next是否为空,因为没有和只有一个元素肯定无法是环 (环至少要两个元素)
  3. 细节:0个或一个元素(容易漏掉)也无法成环

代码

  1. 哈希表法
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) return false;
        Set<ListNode> set = new HashSet<>();
        while (head != null){
            if (!set.add(head)) return true;
            head = head.next;
        }
        return false;
    }
}
  1. 快慢指针法
public class Solution {
    public boolean hasCycle(ListNode head) {
        //只有一个本身为空 肯定无环
         if (head == null || head.next == null) return false;
         //让快慢指针起始位置不同是因为后面的while循环是先判断循环条件,否则不能执行
       ListNode slow = head;
       ListNode fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值