zoukankan      html  css  js  c++  java
  • 141. Linked List Cycle(环形链表,判断链表中是否有环存在)

    Given a linked list, determine if it has a cycle in it.

    Follow up:
    Can you solve it without using extra space?

    给定一个链表,判断链表中是否有环。

    进阶:
    你能否不使用额外空间解决此题?

    ===================================

    更进一步找到环的入口点请看这里:https://blog.csdn.net/qq_34115899/article/details/83240874

    ===================================

    /**
     * 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) {
            if (head == null || head.next == null)   return false;
            ListNode runner = head;
            ListNode walker = head;
            while (runner.next != null && runner.next.next != null) {
                runner = runner.next.next;
                walker = walker.next;
                if (runner == walker)   return true;
            }
            return false;
        }
    }

    如果头结点为空或者只有一个结点,肯定不存在环。

    定义2个指针,一个每次走2步,一个每次走1步,如果前面的指针走到了末尾,肯定不存在环,有环到不了null情况。

    如果有环,那么前面的指针一定在这个环里转圈,后面的指针也会走到这个环里来,他们一定会相遇,此时跳出循环返回true。

    =========================Talk is cheap, show me the code========================

    CSDN博客地址:https://blog.csdn.net/qq_34115899
  • 相关阅读:
    动态代理
    构建一个REST风格的Web服务(Building a RESTful Web Service)
    使用Spring Boot构建应用程序(Building an Application with Spring Boot)
    SpringBoot笔记 三
    SpringBoot笔记 一
    redis的linux安装
    mysql的windows安装
    linux下Redis安装
    上网列表
    shell每日发邮件
  • 原文地址:https://www.cnblogs.com/lcy0515/p/10807845.html
Copyright © 2011-2022 走看看