Linked List Cycle
来源:互联网 发布:cache数据库 东华 编辑:程序博客网 时间:2024/05/17 08:26
思路:采用“快慢指针”查检查链表是否含有环。让一个指针一次走一步,另一个一次走两步,如果链表中含有环,快的指针会再次和慢的指针相遇。
这里需要注意的一点是算法中循环的条件,这是一个很容易被忽略的细节。
1)因为fast指针比slow指针走得快,所以只要判断fast指针是否为空就好。由于fast指针一次走两步(走得太快了,就容易跌倒!),fast.next可能已经为空(当fast为尾结点时),fast.next.next将会导致NullPointerException异常,所以在while循环中我们要判断fast.next是否为空;
2)考虑一个特殊情况,当输入的链表为空时,算法应该返回false,空链表肯定是不含有环的。如果没有fast != null,也会导致fast.next抛出NullPointerException异常。
代码:public boolean hasCycle(ListNode head) { if(head == null){ return false; } ListNode slow = head; ListNode fast = head; while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; if(slow == fast){ return true; } } return false; }
0 0
- leetcode Linked List Cycle & Linked List Cycle ||
- Linked List Cycle II Linked List Cycle
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle II
- [LeetCode]Linked List Cycle
- Linked List Cycle
- LeetCode | Linked List Cycle
- HDU 1020(水题)
- js获取iframe框架中src所指向的文件的內容
- 什么是“引用”?声明和使用“引用”要注意哪些问题?
- Virtio:针对 Linux 的 I/O 虚拟化框架
- IOS7状态栏
- Linked List Cycle
- 八大排序算法及完整c代码—直接插入排序
- 在网页上显示所在地天气预报的html代码
- Hadoop安装配置
- 未来超速列车概念 上下车无需停站
- FLSL2.0学习笔记(一)
- 定制jQuery File Upload为微博式单文件上传
- 【live555】推流者使用的ServerMediaSession类,以及如何产生SDP
- 黑马程序员-----StringBuffer 字符缓存区