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) {

    }



    }
  • 相关阅读:
    HDU 1492 The number of divisors(约数) about Humble Numbers
    HDU 2700 Parity
    HDU 4104 Discount
    _getch() 函数,应用于输入密码敲入回车前修改
    函数指针|指针函数|C文件操作
    20160504
    数组指针|指针数组
    短路运算|字符串操作函数|内存mem操作函数
    C/C++ typedef
    Union
  • 原文地址:https://www.cnblogs.com/ttaall/p/15693755.html
Copyright © 2011-2022 走看看