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

链表中环的入口结点

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


/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead) {
    ListNode *pFast=pHead, *pSlow = pHead;
	while (pFast != nullptr)
	{
		if (pFast->next == nullptr)
			return nullptr;

		pSlow = pSlow->next;   // 慢指针一次一步
		pFast = pFast->next->next;  // 快指针一次2步

		if(pSlow == pFast) // 两者相遇
		{
			pFast = pHead; // 快指针回到链表头
			while (pFast != pSlow) 
			{
				pFast = pFast->next;  // 快慢指针都是一步一步走,直到再次相遇,即为环入口
				pSlow = pSlow->next; 
			}
			return pFast;
		}
	}
	return nullptr;
    }
};

全部评论

相关推荐

2025-12-18 11:59
广州南方学院 C++
牛客78682892...:直接点还好,总比要了简历也不回的强
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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