题解 | #链表中环的入口结点#
链表中环的入口结点
http://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) {
if(!pHead || !pHead->next) return NULL;
// 定义快慢指针指向头
ListNode* fast = pHead;
ListNode* slow = pHead;
while(fast && fast->next) {
// 快指针一次走两步,慢指针一次走一步
fast = fast->next->next;
slow = slow->next;
// 判断是否相遇,相遇则标志相遇点为 index1,链表头结点 index2
if(fast == slow) {
ListNode* index1 = slow;
ListNode* index2 = pHead;
// 根据数学公式推导得,index1和 index2在后面会再相遇一次,让他们向后走即可。
while(index1 && index2) {
// 先判断是否相等,然后再分别向后走
if(index1 == index2) {
return index1;
}
index1 = index1->next;
index2 = index2->next;
}
}
}
return nullptr;
}
};
查看17道真题和解析