141. Linked List Cycle
2016-03-05 21:58
429 查看
Problem:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Analysis:
利用快慢双指针,如果有环则快指针会追上慢指针,否则快指针先到达链表尾。
Answer:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Analysis:
利用快慢双指针,如果有环则快指针会追上慢指针,否则快指针先到达链表尾。
Answer:
/** * 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 || head.next==null) return false; ListNode slow = head; ListNode fast = head; while(fast!=null && fast.next!=null){ slow = slow.next; fast = fast.next.next; if(fast==slow) return true; } return false; } }
相关文章推荐
- C++设计模式之桥接模式
- Jenkins+Gradle实现android开发持续集成、打包
- Linux Mint 17.2 文本编辑器中文乱码问题
- 查找算法3-2
- andriod 资源文件之存取操作
- const常量和#define宏常量的区别
- c语言中数组与sizeof()
- Matlab人脸检测方法(Face Parts Detection)详解
- [Regex Expression] Tagline --- {0, } {1,10}
- JAVA数据结构---单链表
- JAVA数据结构---单链表
- JAVA数据结构---单链表
- JAVA数据结构---单链表
- JAVA数据结构---单链表
- JAVA数据结构---单链表
- JAVA数据结构---单链表
- JAVA数据结构---单链表
- Linux内核分析 实验二:完成一个简单的时间片轮转多道程序内核代码
- Activity启动系统服务
- 前端学习总结(二十)那些你可能不知道却强大方便的WebStorm快捷键