题解 | #链表中环的入口结点# C++ 解法,链表环入口
链表中环的入口结点
http://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
题解 | #链表中环的入口结点#
C++ 解法,链表环入口
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
if (pHead == nullptr || pHead->next == nullptr) return nullptr;
ListNode *slow = pHead, *fast = slow;
while (fast) {
fast = fast->next;
if (fast) {
slow = slow->next;
fast = fast->next;
}
if (slow == fast) { // 若进入,则有环
fast = pHead;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
}
return nullptr;
}
};
查看26道真题和解析