剑指offer--链表中环的入口结点

xiaoxiao2021-02-28  36

题目描述

一个链表中包含环,请找出该链表的环的入口结点。

/* 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(fast == slow) break; } if(fast == NULL || fast->next == NULL) return NULL; fast = pHead; while(fast != slow){ fast = fast->next; slow = slow->next; } return slow; } };
转载请注明原文地址: https://www.6miu.com/read-2650152.html

最新回复(0)