【leetcode刷题】T107-环形链表 II

时间:2022-06-26
本文章向大家介绍【leetcode刷题】T107-环形链表 II,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

【题目】

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

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

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

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

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

【思路】

我们使用【T106-环形链表】的方法,找到first和second指针相遇点(first指针每次移动一步,second移动两步)。

如图所示,假设头结点到环入口的距离为a,环入口到相遇点的距离为b,环的长度为C。

那么first指针移动步数为a+b+nC

second指针移动步数为a+b+mC

并且有second指针移动步数是first的两倍,即a+b+mC = 2*(a+b+nC)

有a = (m-n)C - b = (m-n-1)C + (C-b)

因此,first指针重新指向头结点,second指针位置不变,两指针每次移动一步,那么再次相遇时,所在节点为环入口。

【代码】

python版本

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None
        # 2*(a+b+nC) = a+b+mC
        # ==> a = (m-n)C - b
        # 找到重复节点后,first指针指向头结点
        # first、second两指针都每次移动一步,相遇点即是环入口
        first = head
        second = head
        while True:
            if not second.next or not second.next.next:
                return None
            first = first.next
            second = second.next.next
            if first == second:
                break

        first = head
        while first != second:
            first = first.next
            second = second.next
        return first

C++版本

/**
 * 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) {
        if(!head)
            return NULL;
        // 2*(a+b+nC) = a+b+mC
        // ==> a = (m-n)C - b
        // 找到重复节点后,first指针指向头结点
        // first、second两指针都每次移动一步,相遇点即是环入口
        ListNode* first = head;
        ListNode* second = head;
        // 找到相遇点
        while(true){
            if(!second->next || !second->next->next)
                return NULL;
            first = first->next;
            second = second->next->next;
            if(first == second)
                break;
        }

        // first指向头结点,两指针每次移动一步
        first = head;
        while(first != second){
            first = first->next;
            second = second->next;
        }
        return first;
    }
};