leetcode-142 环形链表II

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

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

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

示例 1:

输入:head = [3,2,0,-4], pos = 1 输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。

在这里插入图片描述

方法一: 集合set进行环的判断
当想要插入节点到set中之前需确认set中没有当前节点,如果有则为环,没有即可插入

ListNode *detectCycle(ListNode *head) {
    if (head == NULL) return NULL;
    
    set<ListNode *> node_set;
    node_set.insert(head);
    head = head -> next;
    while(head) {
        if (node_set.find(head) == node_set.end()) {
            node_set.insert(head);
        } else {
            return head;
        }
        head = head -> next;
    }
    return NULL;
}

方法二:快慢指针

ListNode *detectCycle(ListNode *head) {
    ListNode *fast = head;
    ListNode *slow = head;
    ListNode *meet = NULL;
    while(fast && slow) {
        fast = fast -> next;
        slow = slow -> next;
        if (fast) {
            fast = fast -> next;
            if (fast == slow) { //找到相遇的节点
                meet = fast;
                break;
            }
        } else {
            return NULL;
        }
    }
    
    if (meet == NULL) {
        return NULL;
    }
	
	/*两个指针分别从相遇节点和头节点一起移动,当相等时则为环的起始节点*/
    while(!(meet == head)) { 
        meet = meet -> next;
        head = head -> next;
    }
    return meet;
}
发布了239 篇原创文章 · 获赞 17 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Z_Stand/article/details/104182523