【题目描述】
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
【解法】
1.哈希法
unordered_set可以把它想象成一个集合,它提供了几个函数让我们可以增删查:
unordered_set::insert
unordered_set::erase
unordered_set::find
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
unordered_set<ListNode*> st;
while (pHead) {
//pHead没有出现在st中时,进入if
if (st.find(pHead) == st.end()) {
st.insert(pHead);
pHead = pHead->next;
}
else {
return pHead;
}
}
return nullptr;
}
};
2.双指针法
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
ListNode *fast = pHead;
ListNode *slow = pHead;
//*********************************************************//
//if (!fast || !fast->next) return nullptr;//这句放这也可 //
//********************************************************//
//思想:因为如果是
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) break;
}
if (!fast || !fast->next) return nullptr;
fast = pHead;
while (fast != slow) {
fast = fast->next;
slow = slow->next;
}
return fast;
}
};