Linked List Cycle I II
2015-07-11 22:31
302 查看
Follow up:
Can you solve it without using extra space?
list, faster pointer will end up in catching up with slower pointer. If the linked list is an acyclic list, faster pointer will reach null in the end.
/** * 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) return false; ListNode slower = head; ListNode faster = head; while (faster.next != null && faster.next.next != null) { slower = slower.next; faster = faster.next.next; if (slower == faster) return true; } return false; } }Linked
List Cycle II
null.
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 ListNode detectCycle(ListNode head) { if (head == null) return null; ListNode faster = head; ListNode slower = head; while (faster.next != null && faster.next.next != null) { slower = slower.next; faster = faster.next.next; if (slower == faster) { slower = head; while (slower != faster) { slower = slower.next; faster = faster.next; } return slower; } } return null; } }
相关文章推荐
- MVC框架
- JDBC入门
- 红黑树(3) - 删除操作
- leetcode100 Same Tree
- tinyhttpd学习笔记(一)编译错误及运行结果
- Linux 常用命令(2)
- 黑马程序员——高新技术---Java基础—常用类—Stirng类,StringBuffer类
- 异常分析
- R.java 文件的错误
- Java学习笔记
- yum命令安装mysql
- python3自带web服务器
- hdu 4495 - Rectangle(hash+二分+dp)
- 【 D3.js 入门系列 — 2.1 】 选择、插入、删除元素
- 【数据可视化】大规模多变量空间数据场可视化2
- leetoj Remove Duplicates from Sorted Array
- iOS中的事件处理
- 设计复杂的 iOS 动画效果
- 利用内存结构及多线程优化多图片下载(IOS篇)
- 【Big Data】HADOOP集群的配置(一)