首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Leetcode 题目解析之 Linked List Cycle

Leetcode 题目解析之 Linked List Cycle

原创
作者头像
ruochen
发布2022-01-14 11:36:29
发布2022-01-14 11:36:29
1.3K0
举报

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

Follow up:

Can you solve it without using extra space?

快慢指针,定义两个指针,一个每次走一步,另一个每次走两步。如果快指针“遇到”了慢指针,说明有环。

代码语言:javascript
复制
    public boolean hasCycle(ListNode head) {

        if (head == null) {
            return false;
        }

        ListNode slow = head;
        ListNode fast = head.next;

        while (fast != null) {

            if (fast.next == null || fast.next.next == null) {
                return false;
            }

            if (slow == fast) {
                return true;
            }

            fast = fast.next.next;
            slow = slow.next;
        }

        return false;
    }

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档