LeetCode - Linked List Cycle

时间:2014-10-27 22:49:16   收藏:0   阅读:154

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

 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 };

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!