判断链表中是否有环和环的入口

时间:2024-11-27 07:05:16

1.判断链表中是否有环

快慢指针循环即可,快慢指针重合有环


class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *slow=head;
        ListNode *fast=head;
        while (fast&&fast->next) {
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast) return true;
        }
        return false;
    }
};

2.求环的入口

class Solution {
  public:
    ListNode* EntryNodeOfLoop(ListNode* pHead) {
        ListNode* slow = pHead;
        ListNode* fast = pHead;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast)
            {
                ListNode *index=pHead;
                while (index!=fast) {
                    index=index->next;
                    fast=fast->next;
                }
                return fast;
            }
        }
        return fast=nullptr;
    }
};