博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

LeetCode【141】Linked List Cycle

Posted on 2015-05-08 11:12  NUST小文  阅读(118)  评论(0编辑  收藏  举报

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

快慢步,直接AC代码:

值得注意一下的地方就是if(!p2->next || !p2->next->next),如果p2==NULL,那么p2->next用法是错误的,而||运算符的性质是当前一个条件为真时,第二个条件不再判断。

bool hasCycle(ListNode *head) {
        if(!head || !head->next)
            return false;
        ListNode *p1= head;
        ListNode *p2= head;
        while(p2)
        {
            
            if(!p2->next || !p2->next->next)
                return false;
            p2=p2->next->next;
            p1=p1->next;
            if(p1==p2)
                return true;
        }
        return false;
    }