[LeetCode]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?

解题方案:

使用快慢指针,如果有环,快指针肯定会追上慢指针。下面是该题的代码:

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

 

posted @ 2014-10-14 23:00  skycore  阅读(147)  评论(0编辑  收藏  举报