zoukankan      html  css  js  c++  java
  • Leecode no.142 环形链表 II

    package leecode;

    import java.util.HashSet;
    import java.util.Set;

    /**
    * 142. 环形链表 II
    *
    * 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
    *
    * 如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
    *
    * 不允许修改 链表。
    *
    * @author Tang
    * @date 2021/12/15
    */
    public class DetectCycle {

    /**
    * 玩不起了 直接用散列表判断是否存在环
    *
    * @param head
    * @return
    */
    public ListNode detectCycle(ListNode head) {
    Set set = new HashSet();

    while(head != null) {
    if(set.contains(head)) {
    return head;
    }
    set.add(head);
    head = head.next;
    }
    return null;
    }

    /**
    * 双指针判断是否存在环
    *
    * @param head
    * @return
    */
    public Boolean detectCycle2(ListNode head) {

    ListNode fast = head;
    ListNode slow = head;

    while(fast != null && fast.next != null) {
    //快指针走两步
    fast = fast.next.next;
    //慢指针走一步
    slow = slow.next;
    if(slow == fast) {
    return true;
    }
    }
    return false;

    }

    public static void main(String[] args) {

    }



    }
  • 相关阅读:
    深入学习Motan系列(二)——服务发布
    深入学习Motan系列(一)——入门及知识zookeeper储备
    Guava Cache 总结
    Jetty学习(一)
    群发百万邮件
    Project ACRN documentation
    Storage Performance Development Kit
    DPDK Test Plans
    golang 判断前缀后缀、包含关系
    golang multiconfig 示例
  • 原文地址:https://www.cnblogs.com/ttaall/p/15693755.html
Copyright © 2011-2022 走看看