LeetCode 之 Linked List Cycle I II — C++ 实现

来源:互联网 发布:童话淘宝店 编辑:程序博客网 时间:2024/04/29 04:04

Linked List Cycle

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

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

给定一个链表,验证是否存在环。

附加:

能否不额外分配空间。

分析:

    维护两个指针,ne 每次移动两个节点,pre 每次移动一个节点,则 ne 是 pre 的 2 倍,若有环,pre 和 ne 一定会相遇。

class Solution {public:    bool hasCycle(ListNode *head) {        if(!head)        {            return false;        }                ListNode *pre = head, *ne = head;        //ne速度是pre速度的2倍,若有环一定会相遇        while(ne->next)        {            pre = pre->next;            if(ne->next->next)            {                ne = ne->next->next;                if(pre == ne)                {                    return true;                }            }            else //链表有尾,则没有环            {                break;            }        }                return false;    }};

Linked List Cycle II

 

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

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

给定一个链表,验证是否存在环。

附加:

能否不额外分配空间。

分析:

    维护两个指针,ne 每次移动两个节点,pre 每次移动一个节点,则 ne 是 pre 的 2 倍,若有环,pre 和 ne 一定会相遇。设表头 X,Y 为环入口,Z 为 pre 和 ne 相遇点,则他们通过的距离 Lpre = a+b, Lne = a+b+c, ne是 pre 的 2 倍,则 Lne = 2Lpre, 所以 a = c.因此,当第一次相遇时,pre 继续向前走,ne 重新从表头开始走,则再次相遇点就是环的起点。(图为转载)

class Solution {public:    ListNode *detectCycle(ListNode *head) {        if(!head)        {            return NULL;        }                bool hasCycle = 0;        ListNode *pre = head, *ne = head;        //ne 速度为 pre 的2倍,有环一定相遇        while(ne->next)        {            pre = pre->next;            if(ne->next->next)            {                ne = ne->next->next;                if(pre == ne)//有环                {                    hasCycle = true;                    break;                }            }            else            {                break;            }        }        //如存在环,ne从头开始走,pre继续走,则相遇在环起点处        if(hasCycle)        {            ne = head;            while(ne != pre)            {                pre = pre->next;                ne = ne->next;            }                        return pre;        }                return NULL;    }};

0 0
原创粉丝点击