62_leetcode_Linked List Cycle

来源:互联网 发布:模拟城市mac破解 编辑:程序博客网 时间:2024/06/05 14:22

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

Follow up:

Can you solve it without using extra space?

1:特殊情况;2:两个指针,slow,fast, 每一次slow走一步,fast走两步;如果两者相等的话,存在cycle;如果fast存在NULL的情况,则说明没有cycle

        bool hasCycle(ListNode *head)    {        if(head == NULL || head->next == NULL)        {            return false;        }                ListNode *slowNode = head;        ListNode *fastNode = head;        while(fastNode && fastNode->next)        {            slowNode = slowNode->next;            fastNode = fastNode->next->next;            if(slowNode == fastNode)            {                return true;            }        }        return false;    }


0 0
原创粉丝点击