网站开发域名,wordpress 说说 分页,自媒体营销模式有哪些,着力规范网站集约化建设leetcode142. 环形链表 II
题目 思路
集合法
将节点存入set#xff0c;若重复出现则说明是环
快慢指针法
分别定义 fast 和 slow 指针#xff0c;从头结点出发#xff0c;fast指针每次移动两个节点#xff0c;slow指针每次移动一个节点#xff0c;如果 fast 和 slow指…leetcode142. 环形链表 II
题目 思路
集合法
将节点存入set若重复出现则说明是环
快慢指针法
分别定义 fast 和 slow 指针从头结点出发fast指针每次移动两个节点slow指针每次移动一个节点如果 fast 和 slow指针在途中相遇 说明这个链表有环。初次相遇后将slow设为头结点slow和fast这两个指针每次只走一个节点 当这两个指针相遇的时候就是环形入口的节点。
代码
集合法
class Solution:def detectCycle(self, head: Optional[ListNode]) - Optional[ListNode]:node_set set()current headwhile current:if current in node_set:return currentelse:node_set.add(current)current current.nextreturn None快慢指针法
class Solution:def detectCycle(self, head: ListNode) - ListNode:slow headfast headwhile fast and fast.next:slow slow.nextfast fast.next.next# If there is a cycle, the slow and fast pointers will eventually meetif slow fast:# Move one of the pointers back to the start of the listslow headwhile slow ! fast:slow slow.nextfast fast.nextreturn slow# If there is no cycle, return Nonereturn None