141. Linked List Cycle

来源:互联网 发布:华藏卫视网络直播 编辑:程序博客网 时间:2024/05/10 21:17

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

Follow up:
Can you solve it without using extra space?

这道题用两个指针指向表头,一个每次走一步,一个每次走两步,如果这个链表有环的话,那么快的指针会赶上慢的指针。
程序要防止指针为空的情况。

class Solution {public:    bool hasCycle(ListNode *head)     {        ListNode *slow=head;        ListNode *fast=head;        while(slow&&fast&&fast->next!=NULL)        {            slow=slow->next;            fast=fast->next->next;            if(slow==fast)                return true;        }        return false;    }};
0 0
原创粉丝点击