

Linked List Cycle
source link: http://yeziahehe.com/2020/03/11/LinkedListCycle/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

时间复杂度: O(n), 空间复杂度: O(1)
解题思路
这是一道经典的链表题目 - 环形链表,基本的解题思路是双指针技巧里面的快慢指针。
- 如果没有环,快指针将停在链表的末尾。
- 如果有环,快指针最终将与慢指针相遇。
这两个指针的适当速度应该是多少?
一个安全的选择是每次移动慢指针一步,而移动快指针两步。每一次迭代,快速指针将额外移动一步。如果环的长度为 M,经过 M 次迭代后,快指针肯定会多绕环一周,并赶上慢指针。
public class ListNode { public var val: Int public var next: ListNode? public init(_ val: Int) { self.val = val self.next = nil } } class Solution { func hasCycle(_ head: ListNode?) -> Bool { if head == nil || head?.next == nil { return false } var slow = head var fast = head?.next while fast?.next != nil && fast?.next?.next != nil { slow = slow?.next fast = fast?.next?.next if slow === fast { return true } } return false } }
Recommend
-
53
说明: 如果仔细阅读完全文后,可能感觉有些不统一,这里先说明下原因。 链表尾引用不统一:在介绍单链表时,只有一个链表首部的引用(head) 指向第一个节点。你看到后面关于双链表及循环列表时,除了指向第一个...
-
10
题目¶ 原题地址:https://leetcode.com/problems/design-linked-list/ De...
-
10
解法¶ 遍历链表,记录访问过的节点,找出环开始的节点...
-
18
题目¶ 原题地址:https://leetcode.com/problems/reverse-linked-list/
-
15
Prerequisites To learn about a singly linked list, you should know: Python 3 OOP concepts What are singly linked lists? In this tutorial, we will learn about what singly linked lists are and...
-
17
Prerequisites To learn how to reverse singly linked lists, you should know: Python 3 Python data structures - List In place list reversal...
-
13
Prerequisites To learn about singly linked lists, you should know: Python 3 OOP concepts Singly linked list - inserting a node and p...
-
4
Building a Linked List in Python with Examples Jan 18 Originally published at
-
8
How to find if a linked list is circular has a cycle or ends Suppose that you are given a linked list that is either circular or or not circular (another word for not circular is acyclic...
-
5
Detecting Linked List Cycle. (LeetCode)NotificationsCheck what is trending in the tech world today! Tune in to TechBeat 🎵Last Monday at 4:56 PMRecently laid off from a tech company?...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK