141. Linked List Cycle(环形链表,判断链表中是否有环存在)
发布日期:2021-06-30 19:56:13 浏览次数:2 分类:技术文章

本文共 1045 字,大约阅读时间需要 3 分钟。

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

Follow up:

Can you solve it without using extra space?

 

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

进阶:

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

 

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

更进一步找到环的入口点请看这里:

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

/** * 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========================

转载地址:https://liuchenyang0515.blog.csdn.net/article/details/83240579 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:142. Linked List Cycle II(环形链表2,找到环的入口点并且推理验证)
下一篇:关于AtomicInteger里面addAndGet如何保证同步的(compareAndSwapInt原理)

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月14日 17时22分49秒