鏈表之環形鏈表


上題目:

leetcode 141 簡單

 

 

總體思路:

雙指針,即通過使用一快一慢不同速度的兩個指針來遍歷鏈表,如果有環,快的總會與慢的相遇。

上代碼:

 1 class Solution:
 2     def has_cycle(self, head):
 3         """
 4         :type head:ListNode
 5         :rtype:bool
 6         """
 7         if head == None:
 8             return False
 9         
10         fast, slow = head, head
11         # 這里快指針fast一次走兩步,慢指針slow一次走一步
12         while fast.next != None and fast.next.next != None:
13             slow = slow.next
14             fast = fast.next.next
15             if slow == fast:
16                 return True
17                 
18         return False

 

題目Ⅱ:

leetcode 142 中等

 

 

總體思路:

待解決

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM