[leetcode] #141 Linked List Cycle
2015-10-14 10:02
344 查看
[leetcode] #141 Linked List Cycle
Given a linked list, determine if it has a cycle in it.Follow up:
Can you solve it without using extra space?
用O(1)空间,判断单链表是否存在环
解题思路:
1、fast指针走两步, low指针走一步
2、循环后,若有环则存在fast指针追上low指针那一刻。
至于为何走两步,而不走3步,4步
fast指针每次都比low指针多走一步,若有环,假设一开始差距为n。则每次都缩减一步,当差距为0时,自然两者重合了,走3步,4步, 若n不能整除(3-1)或(4-1)需更多圈才能重合。
[code]/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { ListNode *low = head; ListNode *fast = head; while (low && fast && fast->next) { low = low->next; fast = fast->next->next; if (low == fast) { return true; } } return false; } };
相关文章推荐
- 查看udid方式
- 用ant打包
- 用ant打包
- css3 box-sizing属性
- hdf5 api
- ADO.NET入门教程(五) 细说数据库连接池
- MFC使用SendMessage()发送自定义消息实现进程间通信
- 笔记本外接显示器“水波纹”闪烁
- Django-Rest-Framework 教程: 快速入门
- Ehcache 整合Spring 使用页面、对象缓存
- linux下mysql的root密码忘记解决方
- 会话跟踪--cookie
- 新闻发布系统完结总结
- VC多线程编程
- onethink在安装时不能正常跳转的问题
- 让网络文件系统显示在你的资源管理器中
- centos7 搭建ntp时钟服务
- EhCache 分布式缓存/缓存集群
- Web Services 系列教程
- git笔记(0)