Linked List Cycle II

来源:互联网 发布:现代汉语知乎 编辑:程序博客网 时间:2024/06/08 10:31

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?

这题和上一题不一样,我们要返回圈的初始节点。

首先我们先判断是不是一个环,那么我们可以得到这个环中的一个节点。

那么 我们就能根据这个节点 得到这个环中的节点数。那么就可以像求一个链表中第k个节点一样,用两个指针得到。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *detectCycle(ListNode *head) {        ListNode *pFirst = head;        ListNode *pSecond = head;        ListNode *pCircle = NULL;        while(pFirst!=NULL&&pSecond!=NULL)        {            pFirst = pFirst->next;            pSecond = pSecond->next;            if(pSecond!=NULL)                pSecond = pSecond->next;            else return NULL;            if(pFirst==pSecond)            {                pCircle = pFirst;                break;            }        }        if(!pCircle) return NULL;        ListNode *pCur = pCircle->next;        int len = 1;        while(pCur!=pCircle)        {            pCur = pCur->next;            len++;        }        pFirst = head;        pSecond = head;        for(int  i =0;i<len;i++)            pSecond = pSecond->next;        while(pFirst!=pSecond)        {            pFirst = pFirst->next;            pSecond = pSecond->next;        }        return pSecond;    }};


0 0