LeetCode - Linked List Cycle

判断一个链表是否为循环链表。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         ListNode *fast = head;
13         ListNode *slow = head;
14         while (fast != NULL && fast->next != NULL)
15         {
16             slow = slow->next;
17             //每次fast比slow快一步
18             //直到fast == slow
19             fast = fast->next->next;
20             if (slow == fast)
21                 return true;
22         }
23         return false;
24     }
25 };

 

posted @ 2014-10-27 21:58  bournet  阅读(130)  评论(0编辑  收藏  举报