博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
142. Linked List Cycle II - Medium
阅读量:6721 次
发布时间:2019-06-25

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

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Note: Do not modify the linked list.

 

Example 1:

Input: head = [3,2,0,-4], pos = 1Output: tail connects to node index 1Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = [1,2], pos = 0Output: tail connects to node index 0Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1Output: no cycleExplanation: There is no cycle in the linked list.

 

Follow up:

Can you solve it without using extra space?

 

Floyd's cycle detection algorithm, aka Tortoise and Hare Algorithm

ref: 

time: O(n), space: O(1)

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode detectCycle(ListNode head) {        ListNode slow = head, fast = head, start = head;        while(fast != null && fast.next != null) {            fast = fast.next.next;            slow = slow.next;            if(fast == slow) {                while(slow != start) {                    slow = slow.next;                    start = start.next;                }                return start;            }        }        return null;    }}

 

转载于:https://www.cnblogs.com/fatttcat/p/10181196.html

你可能感兴趣的文章
Dial Menu
查看>>
Clock View
查看>>
一见钟情!Java闭包
查看>>
js中的文档模式-document.compatMode
查看>>
使窗体拥有透明效果的API
查看>>
拦截器方法:自动加载类__autoload()
查看>>
C结构体工具DirectStruct(综合示例一)
查看>>
asm文件夹在那里
查看>>
kubernetes的架构设计
查看>>
Android 剪裁后 onActivityResult 不调用
查看>>
我们为何需要重构代码?
查看>>
APT攻击分析
查看>>
php--------删除一个路径下的所有文件夹和文件
查看>>
程序员的圣诞礼物:计算机寓言之秋
查看>>
Erlang shell 常用编辑指令
查看>>
Android上传文件到PC的简单实例
查看>>
Spring配置文件applicationContext.xml(2)配置详解
查看>>
Mysql 关键字及保留字
查看>>
Gearman及python客户端安装和简单试用
查看>>
何必那样拼命呢?能得到,得不到的,又怎样?!
查看>>