简繁EN

LeetCodeNo. 024

【LeetCode with Python】 141. Linked List Cycle

目錄

題目

原題頁面:https://leetcode.com/problems/linked-list-cycle/
題目型別:Linked List, Two Pointers
難度評價:Medium
類似題目:(M) Linked List Cycle II

Given a linked list, determine if it has a cycle in it.

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


分析

確定連結串列是否有環。記得好像是程式設計之美上的題目?

用兩個指標。一個是快指標,每輪走兩步。一個是慢指標,每輪走一步。如果連結串列有環,則總會有某個時刻,快慢指標會相遇在同一個節點。

如何證明呢?假設現在兩個指標都已經進入了環,快指標每次都比慢指標多走一步。那麼當某個時刻,快指標要麼在慢指標後面一個節點處,要麼在其後面兩個節點處。如果是前者,則下一次兩者就會相遇。如果是後者,則下一次走動後,快指標將位於慢指標後面一個節點處,則又回到了前者的情形。所以兩個指標必然會相遇到環上的某個節點處。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
# @param head, a ListNode
# @return a boolean
def hasCycle(self, head):
if None == head:
return False
fast = slow = head
while True:
fast = fast.next
if None == fast:
return False
fast = fast.next
if None == fast:
return False
slow = slow.next
if fast == slow:
return True

本文地址:https://xnerv.wang/zh-tw/leetcode-linked-list-cycle/