每日一题——带环链表

来源:互联网 发布:java的代理模式作用 编辑:程序博客网 时间:2024/06/06 09:38

判断链表是否带环。
若带环求环的长度。
若带环求环的入口处。

并计算上述问题的时间复杂度

求环的入口处(前面几行代码证明带环)至于环的长度,从之前的推论可知,链表起始到环的入口的距离等于相遇点走到环入口的距离,所以环的长度就等于链表起始点到相遇点的距离(代码中的count)。  ListNode *detectCycle(ListNode *head) {        // write your code here        ListNode* begin = head;        ListNode* last = head;        if(head == NULL || head->next == NULL)        {            return NULL;        }        int count = 0;          while(begin->next != NULL && begin->next->next != NULL)        {            begin = begin->next->next;            last = last->next;            count++;   //记录到相遇点的距离,即环长            if(begin == last)   //相遇点                {                    ListNode* newBegin = head;                    ListNode* newLast = begin;                    while(newBegin != newLast)                    {                        newBegin = newBegin->next;                        newLast = newLast->next;                    }                    return newBegin;                }        }        return NULL;    }

这里写图片描述

时间复杂度:
1>:O(N)
2>:O(N)
3>:O(N^2)

原创粉丝点击