[Swift]LeetCode142. 環形鏈表 II | Linked List Cycle II

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-abkgsoso-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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

Note: Do not modify the linked list.git

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


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

說明:不容許修改給定的鏈表。spa

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


 1 import Foundation
 2 
 3 class LinkedListCycleII {
 4 
 5     public class ListNode {
 6         
 7         public var val: Int
 8         public var next: ListNode?
 9         
10         public init(_ val: Int) {
11             self.val = val
12             self.next = nil
13         }
14     }
15     
16     // Waiting to be judged.
17     func detectCycle(_ head: ListNode?) -> ListNode? {
18         var slow = head
19         var fast = head
20         var h = head
21         while fast != nil && fast?.next != nil {
22             slow = slow?.next
23             fast = fast?.next?.next
24             if slow === fast {
25                 while slow !== head {
26                     h = h?.next
27                     slow = slow?.next
28                 }
29                 return h
30             }
31         }
32         return nil
33     }
34 }
相關文章
相關標籤/搜索