题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
本题要求求出ring的入口节点,比上一道题目多了一个要求
依然是两种做法:
- 使用set存储
如果发现指针之前存储过,可以直接返回当前的指针 - 使用快慢指针
如果快慢指针相遇,则依照最高赞题解的思路,
快慢指针的首次相遇点与环的入口节点之间的距离X等于
phead到环入口节点的距离
代码如下:
class Solution { public: ListNode* EntryNodeOfLoop1(ListNode* pHead) { if (!pHead) return pHead; unordered_set<ListNode *> _set; while (pHead) { _set.emplace(pHead); pHead = pHead->next; if (_set.find(pHead) != _set.end()) { return pHead; } } return pHead; } ListNode* EntryNodeOfLoop(ListNode* pHead) { ListNode *slow; ListNode *fast; fast = slow = pHead; while (fast && fast->next) { fast = fast->next->next; slow = slow->next; if (fast == slow) { break; } } if (!fast or !fast->next) { return nullptr; } fast = pHead; while (fast != slow) { fast = fast->next; slow = slow->next; } return fast; } };