原題地址:http://oj.leetcode.com/problems/linked-list-cycle/
題意:判斷鏈表中是否存在環路。
解題思路:快慢指針技巧,slow指針和fast指針開始同時指向頭結點head,fast每次走兩步,slow每次走一步。如果鏈表不存在環,那么fast或者fast.next會先到None。如果鏈表中存在環路,則由於fast指針移動的速度是slow指針移動速度的兩倍,所以在進入環路以后,兩個指針遲早會相遇,如果在某一時刻slow==fast,說明鏈表存在環路。
代碼:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a boolean def hasCycle(self, head): if head == None or head.next == None: return False slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False