Linked List Cycle
2014-05-05 19:01
344 查看
原题地址: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
阅读更多
相关文章推荐
- 141. Linked List Cycle
- Leetcode Linked List Cycle II
- <leetcode系列> Linked List Cycle II
- Linked List Cycle
- Linked List Cycle leetcode java (链表检测环)
- 【leetcode】【单链表】【142】Linked List Cycle II
- 141. Linked List Cycle*
- 141. Linked List Cycle
- 142. Linked List Cycle II**
- LeetCode 141 Linked List Cycle(链表判环)
- leetcode 之 Linked List Cycle
- LeetCode:Linked List Cycle
- Linked List Cycle
- [Leetcode] Linked List Cycle II (Java)
- [leetcode] Linked List Cycle
- LeetCode-linked-list-cycle-ii
- [leetcode][list][two pointers] Linked List Cycle
- [LeetCode]Linked List Cycle
- (LeetCode)Linked List Cycle --- 判断循环链表
- Linked List Cycle