题解 | #链表中环的入口结点#
链表中环的入口结点
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* fast = pHead; ListNode* slow = pHead; while (fast!=NULL && fast->next != NULL) { fast = fast->next->next; slow = slow->next; if(slow == fast) { // 找到相遇的节点 break; } } if(fast == nullptr || fast->next == nullptr) { return nullptr; } fast = pHead; while(fast != slow) { // 头结点和相遇点到环入口距离一致 fast = fast->next; slow =slow->next; } return fast; } };
数据结构练习 文章被收录于专栏
数据结构练习