LeetCode 142:環形鏈表 II Linked List Cycle II

給定一個鏈表,返回鏈表開始入環的第一個節點。 若是鏈表無環,則返回 nullnode

爲了表示給定鏈表中的環,咱們使用整數 pos 來表示鏈表尾鏈接到鏈表中的位置(索引從 0 開始)。 若是 pos-1,則在該鏈表中沒有環。spa

**說明:**不容許修改給定的鏈表。3d

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.指針

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.code

Note: Do not modify the linked list.blog

示例 1:索引

輸入:head = [3,2,0,-4], pos = 1
輸出:tail connects to node index 1
解釋:鏈表中有一個環,其尾部鏈接到第二個節點。

示例 2:hash

輸入:head = [1,2], pos = 0
輸出:tail connects to node index 0
解釋:鏈表中有一個環,其尾部鏈接到第一個節點。

示例 3:it

輸入:head = [1], pos = -1
輸出:no cycle
解釋:鏈表中沒有環。

進階: 你是否能夠不用額外空間解決此題?io

Follow-up: Can you solve it without using extra space?

解題思路:

和上一道題比只多了一步判斷入環節點在哪。兩種方法:

哈希表:

哈希表添加節點時只要發現節點已經存在了,證實就有環形鏈表。而且已存在的節點即爲入環節點

雙指針:

畫了個圖幫助理解:

一快一慢雙指針開始從頭結點遍歷鏈表,快節點速度爲2,慢節點速度爲1:

相遇時:

慢節點走了:a+b

因爲快指針速度是慢指針的2倍,快節點走了:2(a+b)

快慢節點相遇時快節點比慢節點恰好多走了一圈環形節點。快節點走了:(a+b)+(b+c)

列方程:2(a+b)=(a+b)+(b+c)

解得 a=c

也就是說:相遇節點到入環節點的長度和頭節點到入環節點的長度相等

能夠得出結論,若是此時讓慢節點或快節點中的一個指向頭節點,另外一個留在相遇節點,而後速度都爲1,繼續遍歷鏈表,雙指針再次相遇時的節點恰好是入環節點。

注:爲了理解方便,把長度 b 定爲上半部分長度,實際上 b 應該爲快慢節點相遇時慢節點繞過環形鏈表的總長度

哈希表解題:

Java:

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null) return null;//若是是空鏈表直接返回
        Set<ListNode> nodeSet = new HashSet<>();//構造哈希表
        while (head.next != null) {//鏈表下一個不爲空
            if (nodeSet.contains(head)) return head;//哈希表包含該節點則存在環形鏈表
            nodeSet.add(head);//加入節點
            head = head.next;//下移一位
        }
        return null;
    }
}

Python:

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None:
            return None
        hashSet=set()#構造集合
        while(head.next is not None):
            if head in hashSet:#是否已存在
                return head
            hashSet.add(head)
            head=head.next
        return None

雙指針解題:

Java:

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {//快指針及其下一位是否爲null
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {//若是相同,存在環形鏈表
                slow = head;//指向頭節點
                while (slow != fast) {//繼續遍歷,再次相遇時的節點即爲入環節點
                    slow = slow.next;
                    fast = fast.next;
                }
                return slow;
            }
        }
        return null;
    }
}

Python:

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None or head.next is None:
            return None
        slow, fast = head, head
        while fast is not None and fast.next is not None:
            slow, fast = slow.next, fast.next.next
            if slow == fast:
                slow = head
                while slow != fast:
                    slow = slow.next
                    fast = fast.next
                return slow
        return None

歡迎關注公衆號:愛寫Bug(ID:iCodeBugs)

愛寫bug.png

相關文章
相關標籤/搜索