Entry of the node list to prove safety offer Central

Title Description

To a linked list, wherein if the ring comprises, find the entry ring node list, otherwise, outputs null.

Thinking

  1. Save the establishment of a vector node visited, prior to each iteration vector pressed into the new node, if found the same node is returned, if not, then pushed
  2. Pointer setting speed, starting from the head of the list are, each pointer quickly take two steps, a pointer slow step, if there is a ring, the ring must meet at a point (Conclusion 1). Then let the two pointers are from the meeting point and the head of the list, both of which are replaced each time step, the ring eventually encounter an inlet (Conclusion 2).

Code

method one:

class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead)
    {
        vector<ListNode*> v;
        if(pHead == NULL)
            return NULL;
        v.push_back(pHead);
        pHead = pHead->next;
        while(pHead != NULL)
        {
            for(int i = 0; i < v.size();i++)
            {
                if(pHead == v[i])
                    return pHead;
            }
            v.push_back(pHead);
            pHead = pHead->next;
        }
        return NULL;
    }
};

Method Two:

class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead)
    {
        ListNode*fast=pHead,*low=pHead;
        while(fast&&fast->next){
            fast=fast->next->next;
            low=low->next;
            if(fast==low)
                break;
        }
        if(!fast||!fast->next)return NULL;
        low=pHead;//low从链表头出发
        while(fast!=low){//fast从相遇点出发
            fast=fast->next;
            low=low->next;
        }
        return low;
    }
};
Published 85 original articles · won praise 0 · Views 402

Guess you like

Origin blog.csdn.net/weixin_38312163/article/details/104766170