linked-list-cycle-ii

来源:互联网 发布:奇门排盘软件下载 编辑:程序博客网 时间:2024/06/06 01:04

给定一个链表,如果链表中存在环,则返回到链表中环的起始节点的值,如果没有环,返回null。

您在真实的面试中是否遇到过这个题? 
Yes
样例

给出 -21->10->4->5, tail connects to node index 1,返回10

不使用额外的空间

class Solution {public:    ListNode *detectCycle(ListNode *head) {        if(head==NULL||head->next==NULL) return NULL;        ListNode* slow=head,*fast=head;        bool isCycle=false;        while(fast->next&&fast->next->next){            slow=slow->next;            fast=fast->next->next;            if(slow==fast){                isCycle=true;                break;            }        }        if(isCycle==false) return NULL;        else{            slow=head;            while(slow!=fast){                slow=slow->next;                fast=fast->next;            }            return slow;        }    }};


0 0