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

链表中环的入口结点

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

/*
思路挺简单,通过所以例子需要注意单个循环和左边可能出现空指针的问题
*/
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
#include <iostream>
class Solution {
  public:
    ListNode* EntryNodeOfLoop(ListNode* pHead) {
        ListNode* slow = pHead;
        ListNode* fast = pHead;
        do {
            if (!slow->next || !slow ||!fast) {
                cout << "null";
                return nullptr;
            }
        if (slow->next->val == slow->val) {
                return slow;
        }  
            slow = slow->next;
            if(fast->next->next){
                fast=fast->next->next; 
            }else{
                cout<<"null";
                return nullptr;
            }
            if (fast->val == slow->val) {
                break;
            }
        } while (fast->val != slow->val) ;
        ListNode* begin = pHead;
        while (begin->val != slow->val) {
            begin = begin->next;
            slow = slow->next;
        }
        return begin;
    }
};

全部评论

相关推荐

za_chary:你这个简历写的太强了,建议直接投大厂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务