您的位置:首页 > 其它

leetcode 141. Linked List Cycle

2017-01-13 15:28 169 查看
这道题采用的比较典型的龟兔赛跑的思想,用更快的兔子套乌龟,如果存在环的话就会在兔子最终会抓到乌龟的。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *step_one = head;
ListNode *step_two = head;

while(step_two != NULL && step_two->next != NULL && step_two->next->next != NULL)
{
step_one = step_one->next;
step_two = step_two->next->next;

if(step_one == step_two)
return true;
}

return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 141 linked list cycle