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
  • 相关阅读:
    TableViewCell bug
    iOS系统框架概述
    Cocoapods的安装与使用
    ios开发学习路径
    django第七天总结
    django第六天上课总结
    django第四天
    django第四天上课总结
    django第三天 小记
    django第三天
  • 原文地址:https://www.cnblogs.com/lcy0515/p/10807845.html
Copyright © 2011-2022 走看看