Linked List Cycle II

来源:互联网 发布:u盘坏了怎么恢复数据 编辑:程序博客网 时间:2024/06/10 06:18

Linked List Cycle II


Problem

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

Note: Do not modify the linked list.

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


问题

给定一个链表,返回环的起始结点,如果链表不包含环,则返回空。

注意: 不能修改链表

扩展: 不使用辅助存储空间找到链表中环的起始结点。


解题思路

此题目是链表中的环问题扩展。假设经过m步之后,快慢指针相遇。则由链表中的环问题分析可知: 此时快指针走过的路程为m,慢指针走过的路程为2m。此时如果让快指针回到链表头,两个指针都一次走一步。则经过n步(n不大于m)在环的起点处,两个指针将再次相遇。如下图所示:
这里写图片描述


代码(C++)

class Solution {public:    ListNode *detectCycle(ListNode *head) {        if (!head || !(head->next)) return NULL;        ListNode* slow = head;        ListNode* fast = head;        bool hasCycle = false;        while(fast && fast->next){            fast = fast->next->next;            slow = slow->next;            if(slow == fast){                hasCycle = true;                break;            }        }        if (hasCycle){            fast = head;            while(slow != fast){                slow = slow->next;                fast = fast->next;            }            return slow;        }        return NULL;    }};
0 0
原创粉丝点击