1.這是一個判斷 鏈表中是否有環(huán) 的題目。
鏈接:https://leetcode.com/problems/linked-list-cycle/

141.Linked List Cycle.png
題目的意思就是輸入一個鏈表,然后判斷鏈表是否構(gòu)成了環(huán)狀結(jié)構(gòu)。
這里有三個思路解決這個問題:
1.在限定時間內(nèi)不斷的向后跑,判斷是否能得到等于None值。如果可以得到,判斷它沒環(huán);如果得不到,有環(huán)。
2.使用鍵值對,記錄這個Node。ps:其實集合(Set就可以,插入錯誤,直接判斷有環(huán))
3.使用長短指針的思路。這個待會畫圖解釋,就是一個快車,一個慢車,如果他們兩能相遇的話,判斷是有環(huán)的。
2.題解:
這里給出后面兩個思路的代碼:
思路2:
class Solution:
# 2- 使用字典記錄
def hasCycle(self, head):
dict_list = {}
i = 0
node = head
while node:
if node in dict_list:
# return dict_list[node] # 這里可以直接返回在哪個節(jié)點形成環(huán)
return True
else:
dict_list[node] = i # 記錄鍵值對
i += 1
node = node.next
return False
思路3:
畫圖解釋:

141.Linked List Cycle.jpg
# 3- 使用長短指針記錄
def hasCycle(self, head):
fast = slow = head
while slow and fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
3.完整代碼
查看鏈接:
https://github.com/Wind0ranger/LeetcodeLearn/blob/master/1-List/141-linked-list-cycle.py