码迷,mamicode.com
首页 > 其他好文 > 详细

Linked List Cycle

时间:2015-04-07 15:05:44      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

给定一个链表,判断是否存在环

思路:龟兔赛跑,一个指针兔跑得快,一个指针龟跑得慢,如果有环兔子一定会遇到乌龟(fast == slow),如果没有环兔子一定能到达终点(fast == null)

  1. class Solution {
  2. public:
  3. bool hasCycle(ListNode *head) {
  4. if (head)
  5. {
  6. ListNode* fast = head;
  7. ListNode* slow = head;
  8. while (fast->next != NULL)
  9. {
  10. slow = slow->next;
  11. fast = fast->next->next;
  12. if (fast == NULL )
  13. {
  14. return false;
  15. }
  16. if (fast == slow)
  17. {
  18. return true;
  19. }
  20. }
  21. }
  22. return false;
  23. }
  24. };




Linked List Cycle

标签:

原文地址:http://www.cnblogs.com/flyjameschen/p/c4f1d6d27435e57f32e0d72c30a59803.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!