141. Linked List Cycle 注意边界条件
2016-06-16 21:10
453 查看
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
这里要注意 边界条件由快那个指针确定 不用考虑慢那个 若只考虑快那个一次走两步的情况 那么 一次走两步若next为空 next->next则无法访问
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
这里要注意 边界条件由快那个指针确定 不用考虑慢那个 若只考虑快那个一次走两步的情况 那么 一次走两步若next为空 next->next则无法访问
/** * 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) { //设置两个指针,一个走两步一个走一步 有环必然会存在相等的时候 if(head == NULL){ return false; } if(head->next == head){ return true; } ListNode*t1 = head; ListNode*t2 = head; //这里要注意 边界条件由快那个指针确定 不用考虑慢那个 若只考虑快那个一次走两步的情况 那么 一次走两步若next为空 next->next则无法访问 while(t2->next!=NULL&&t2->next->next!=NULL){ t1 = t1->next; t2 = t2->next->next; if(t1 == t2){ return true; } } return false; } };
相关文章推荐
- [简明] 申请证书
- Linux服务器的关机和重启命令
- cocos2dx 一张图片的闪烁的动画
- 【leetcode】202. Happy Number
- NSOprationQueue 与 GCD 的区别与选用
- PAT乙级练习题B1004.成绩排名
- js 判断存在于原型中的属性
- android之SQLlite操作
- VS2010+OpenCV配置
- 多进程并发服务器
- springMVC:HandlerInterceptor拦截器的使用
- 解决ImportError:cannot import name xmlrpc_client问题
- springMVC:HandlerInterceptor拦截器的使用
- odoo9 继承父类的方法和重写父类的方法
- LSA及pLSA
- 日出
- 前言
- Linux系统时间不准问题分析
- 函数重载、初始化列表、复合类、析构函数
- Enable rewrite in Apache