142. 环形链表 II

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null

说明:不允许修改给定的链表。

进阶:
你是否可以不用额外空间解决此题?

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        //思路1:用set,遍历查找重复的head。
        set<ListNode*>node_set;
        while(head)
        {
            if(node_set.find(head) != node_set.end())
            {
                return head;
            }
            node_set.insert(head);
            head = head->next;
        }
        return NULL;
    }
};
//思路2:快慢指针,当slow==fast,则相遇
class Solution
{
public:
    ListNode *detectCycle(ListNode*head)
    {
        ListNode *fast = head;
        ListNode *slow = head;
        ListNode *meet = NULL;//相遇节点
        while(fast)
        {
            slow = slow->next;
            fast = fast->next;
            if(fast == NULL)
            {
                return NULL;
            }
            fast = fast->next; //fast多走一步;
            if(slow == fast)
            {
                meet = fast; //相遇了
                break;
            }
        }
        if(meet == NULL)
        {
            return NULL;
        }
        while(head && meet)
        {
            if(head == meet)
            {
                return meet;
            }
            head = head->next;
            meet = meet->next;
        }
        return NULL;
    }
    
};

猜你喜欢

转载自blog.csdn.net/qq_38640439/article/details/84554536