美文网首页
141. Linked List Cycle

141. Linked List Cycle

作者: juexin | 来源:发表于2017-01-09 19:01 被阅读0次

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* p1 = head;
        ListNode* p2 = head;
        
        while(p1&&p2&&p2->next)
        {
            p1 = p1->next;
            p2 = p2->next->next;
            
            if(p1==p2)
              return true;
        }
        return false;
    }
};

相关文章

网友评论

      本文标题:141. Linked List Cycle

      本文链接:https://www.haomeiwen.com/subject/gcphbttx.html