Linked List Cycle -- leetcode
2015-06-02 16:47
218 查看
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
基本思路:
快慢两指针。
一个指针每次移动一步,另一个指针每次移动两步。如存在环,必有相遇的时候。
Follow up:
Can you solve it without using extra space?
基本思路:
快慢两指针。
一个指针每次移动一步,另一个指针每次移动两步。如存在环,必有相遇的时候。
/** * 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 *one = head; ListNode *two = head; while (two && two->next) { one = one->next; two = two->next; two = two->next; if (one == two) return true; } return false; } };
相关文章推荐
- Twister—迭代MapReduce
- 第十周项目 3 日期时间类
- Eclipse导入Android签名
- ELF relocatable object file && ELF Executable object file && Run-time Memory Image 的结构
- nginx整合多个tomcat
- Window8 ComboBox 可编辑
- 升级python环境
- setContentView(R.layout.activity_main) Error解决方法
- ArcGIS For Android 定位模块的使用介绍
- 预处理器简介
- [ERROR] Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.3.1:
- CDH5.3.2中配置运行Spark SQL的Thrift Server
- 如何用简单易懂的例子解释隐马尔可夫模型?
- B-tree/B+tree/B*tree [转]
- 实例构造器和类型构造器
- python执行子进程实现进程间通信的方法
- jQuery中$.fn的用法示例介绍
- 数值属性的相异性:闵可夫斯基距离
- iOS 调试
- shmget函数与shmat