LeetCode Linked List Cycle
来源:互联网 发布:淘宝宝贝过期不存在 编辑:程序博客网 时间:2024/06/15 22:31
题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题意:
给定一个单链表,然后确定在这个单链表中是否存在环?发现这道题在面试中经常会出现,因为是单链表,所以要么出现环,要么就没有出现,没有第三种情况出现。所以考虑一种方式,那就是采用类似于跑步一样,就是采用两个指针来做,首先设置一个fast指针和slow指针,然后fast指针每次走两步,而这个slow指针每次走一步,然后判断如果最后fast == slow,那么就说明存在环。也可以理解,类似于跑步跑操场,第一个人以两倍的速度和第二个人赛跑,那么最终在某一个地方,这两个人一定会相遇,也就是说第一个人一定会套圈追上第二个人;第二种情况是如果不存在环,那么无论如何,都一定不可能出现第一个人追上第二个人,也就是结束的条件就是第一个人先到达单链表的尾部。
public static boolean hasCycle(ListNode head){ListNode slow = head;ListNode fast = head;while(fast != null && fast.next != null) //如果有环,那么这个fast和fast的下一个指针一定不会是空{slow = slow.next;fast = fast.next.next;if(slow == fast)break;}return !(fast == null || fast.next == null); //如果没有环,那么这个fast就一定会返回空,所以是false}
0 0
- leetcode Linked List Cycle & Linked List Cycle ||
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- [LeetCode]Linked List Cycle
- LeetCode | Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode: Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode] - Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode]Linked List Cycle
- 【LeetCode】Linked List Cycle
- Linked List Cycle - LeetCode
- 【LeetCode】Linked List Cycle
- Linked List Cycle -- LeetCode
- Objective-C:Foundation
- Python 文档风格
- 博客2
- 在Matlab中使用mex函数进行C/C++混合编程
- CSS3 from W3C学习笔记
- LeetCode Linked List Cycle
- Windows下Mex程序的调试
- matlab获取目录中图像名称及路径的递归实现
- LeetCode:Product of Array Except Self
- BestCoder Round #62 (div.2)Clarke and five-pointed star(极角排序,判断五边形)
- ECMAScript 继承机制实现
- 怎么在win10系统下安装ubuntu双系统
- 在struts2框架做上传功能
- Android手机获取屏幕分辨率(屏幕高度和宽度)