算法:判断是否是循环链表,并返回循环链表开始节点Linked List Cycle II

题目

142. Linked List Cycle II

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

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.

Notice that you should not modify the linked list.

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

Example 1:

在这里插入图片描述

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:
在这里插入图片描述

Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:
在这里插入图片描述

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.

Constraints:

  • The number of the nodes in the list is in the range [0, 104].
  • -105 <= Node.val <= 105
  • pos is -1 or a valid index in the linked-list.

解法一,用set存储对象

把每个节点存储到不可重复集合set中,判断是否存在即可。但是存储比较多,速度就会稍微慢一点。

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

class LinkedListCycleII:
    def detectCycle(self, head: ListNode) -> ListNode:
        nodeSet = set()
        while head :
            if head in nodeSet:
                return head
            nodeSet.add(head)
            head = head.next

        return Non

解法二,快慢指针

定义两个指针慢和快。 两者都是从头节点开始的,快是慢的两倍。 如果到达末尾,则表示没有周期,否则最终它将最终赶上周期中某个地方的慢速指针。

假设从第一个节点到开始循环的节点的距离为A,并且慢速指针行进为A + B。 快速指针必须经过2A + 2B才能赶上。 周期的大小为N。完整的周期也是相交的慢速指针经过的时间比慢速指针经过了多少。

A + B + N = 2A + 2B
N = A + B
根据我们的计算,慢速指针在遇到快速指针时会精确地经过整个周期,并且由于它最初在循环开始之前就经过了A,因此它必须经过A才能到达循环开始的点! 我们可以在头节点处启动另一个慢速指针,然后移动两个指针,直到它们在循环开始时相遇为止。
在这里插入图片描述

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

    def  detectCycleWithTwoPointer(self, head: ListNode) -> ListNode:
        slow, fast = head, head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
               slow2 = head
               while slow2 != slow:
                   slow = slow.next
                   slow2 = slow2.next
               return slow

        return None

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值