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

Linked List Cycle

时间:2014-08-11 20:45:12      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   io   div   amp   log   

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

思路:使用两个指针slow和fast,分别以1和2的速度遍历链表。若链表中存在环,则两个指针必然会在某时刻相遇。

 1 class Solution {
 2 public:
 3     bool hasCycle(ListNode *head) {
 4         if( !head || !head->next ) { return false; }
 5         ListNode *slow = head, *fast = head;
 6         while( fast ) {
 7             slow = slow->next;
 8             fast = fast->next;
 9             if( fast ) { fast = fast->next; }
10             if( fast && fast == slow ) { return true; }
11         }
12         return false;
13     }
14 };

 

Linked List Cycle,布布扣,bubuko.com

Linked List Cycle

标签:style   blog   color   使用   io   div   amp   log   

原文地址:http://www.cnblogs.com/moderate-fish/p/3905264.html

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