博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode] Linked List Cycle
阅读量:4659 次
发布时间:2019-06-09

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

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

Follow up:

Can you solve it without using extra space?

 

[Thoughts]

有一种使用两个指针的方法,一个fast指针,每次移动两步;一个slow指针,每次移动一步。如果两个指针能相遇,则链表具有一个环形。

public boolean hasCycle(ListNode head) {    ListNode faster = head;    ListNode slower = head;    while (faster != null)    {        faster = faster.next;        if (faster == null)        {            return false;        }        else        {            faster = faster.next;        }        slower = slower.next;        if (faster == slower)        {            return true;        }    }    return false;}

 

另一种方法(只是开玩笑)

public class Solution {    public boolean hasCycle(ListNode head) {        if(head == null)            return false;        int i = 0;        while(head.next != null){            i++;            if (i > 10000){                return true;            }            head = head.next;        }        return false;    }}

 

转载于:https://www.cnblogs.com/andrew-chen/p/4226048.html

你可能感兴趣的文章
2018.10.30 NOIp模拟赛 T1 改造二叉树
查看>>
九度oj 题目1074:对称平方数
查看>>
Zookeeper原理 二
查看>>
android之APP+JNI+Drv框架
查看>>
三阶魔方公式
查看>>
BP算法
查看>>
P1855 榨取kkksc03
查看>>
JAVA运行时动态加载类
查看>>
linux ifconfig -a
查看>>
MySql通过数据库文件恢复数据库
查看>>
ASP.NET网站和ASP.NET应用程序的区别
查看>>
Codeforces633G(SummerTrainingDay06-I dfs序+线段树+bitset)
查看>>
iOS判断手机某个App是否存在和常用scheme
查看>>
6 实现微信公众号 自动回复功能
查看>>
51Nod 1212无向图最小生成树
查看>>
hdu 4542 小明系列故事——未知剩余系
查看>>
Symbian UI 架构分类
查看>>
SVM入门(三)线性分类器Part 2
查看>>
mysql 执行 cannot found mac安装mysql的两种方法(含配置)
查看>>
BZOJ 1984: 月下“毛景树”( 树链剖分 )
查看>>