题解 | #链表中环的入口结点#

链表中环的入口结点

http://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4


/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    
    bool has_ring(ListNode* pHead){
        ListNode *slow = pHead, *fast = pHead;
        if(!pHead||!pHead->next||!pHead->next->next) return false;
        fast = fast->next->next;
        while(slow&&fast->next->next){
            if(slow == fast) return true;
            slow = slow->next;
            fast = fast->next->next;
        }
        return false;
    }
    
    ListNode* EntryNodeOfLoop(ListNode* pHead) {
        ListNode *slow = pHead, *fast = pHead;
        if(!has_ring(pHead)) return nullptr;
        //fast = fast->next->next;
        while(slow){
            
            slow = slow->next;
            fast = fast->next->next;
            if(slow==fast){
                fast = pHead;
                break;
            }
        }
        
        while(slow){
            if(slow==pHead) return pHead;
            if(slow == fast) return slow;
            slow = slow->next;
            fast = fast->next;
        }
        
       return pHead; 
        
    }
};













全部评论

相关推荐

04-06 11:24
已编辑
太原学院 C++
点赞 评论 收藏
分享
03-25 16:22
南华大学 Java
不敢追175女神:你是打了上千个招呼吧?😂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务