LeetCode题解:Linked List Cycle
2016-03-04 09:02
381 查看
/**
* 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 walker = head;
ListNode runner = head;
while(runner.next!=null && runner.next.next!=null) {
walker = walker.next;
runner = runner.next.next;
if(walker==runner) return true;
}
return false;
}
}
题意:判断链表是否有环
解题思路:快慢指针,若存在环,两指针必定相遇
代码:
* 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 walker = head;
ListNode runner = head;
while(runner.next!=null && runner.next.next!=null) {
walker = walker.next;
runner = runner.next.next;
if(walker==runner) return true;
}
return false;
}
}
题意:判断链表是否有环
解题思路:快慢指针,若存在环,两指针必定相遇
代码:
/** * 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 walker = head; ListNode runner = head; while(runner.next!=null && runner.next.next!=null) { walker = walker.next; runner = runner.next.next; if(walker==runner) return true; } return false; } }
相关文章推荐
- JavaScript、jQuery与Ajax的关系
- OC如何实现多继承
- Lattice paths
- 初探JVM之java内存区域
- php数据类型
- RTTI
- 你必须知道的Unity引擎知识
- Sublime Text 3配置与vim模式(待完整)
- Pansoft 启动成功但是登录时提示 Cannot read property 'charCodeAt' of null
- 基于zepto的移动端轻量级日期插件--date_picker
- 安卓移动端微信支付集成,遇到很多坑,走了很多弯路
- 位运算
- Codeigniter中集成smarty和adodb的方法
- 循序渐进的敏捷-每日例会
- hadoop错误-Java heap space at org.apache.hadoop.io.BoundedByteArrayOutputStream
- iOS gcd
- 分模块创建maven项目(一)
- Eclipse中输入系统变量和运行参数
- shell while loop
- 初入android,android studio熟悉(二)