Leetcode-Linked List Cycle-Python
2017-08-23 11:48
274 查看
Linked List Cycle
判断单链表是否存在环。Description
解题思路:
一个单链表如果不存在环,则最后一个元素的下一个节点必然为null.
如果单链表存在环,则:
设置两个指针,一个慢指针和一个快指针。将链表的环想象成是一个圆形操场,两个人在同一起跑线开始绕着操场无限循环跑,那么快的人必然会再一次和慢的人相遇,即快指针的元素和慢指针的元素相同时,即说明存在环。
在代码中,慢指针设置为每次走一步,即slow=slow.next,快指针设置为每次走两步,即fast=fast.next.next。实际步数设置是可以任取的,只是循环次数不同,如可以设置fast=fast.next.next.next。
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ if head==None: return False slow = head fast = head while fast.next and fast.next.next: slow = slow.next fast = fast.next.next if slow==fast: return True return False
改进:
由于每次循环都要判断是否到达最后一个节点,因此leetcode上提供了另一种思路,即采取异常的方式。
“Easier to ask for forgiveness than permission.”
def hasCycle(self, head): try: slow = head fast = head.next while slow is not fast: slow = slow.next fast = fast.next.next return True except: return False
相关文章推荐
- 【LeetCode】【Python】Linked List Cycle
- 【LeetCode with Python】 Linked List Cycle
- leetcode 【 Linked List Cycle II 】 python 实现
- [Leetcode][python]Linked List Cycle/Linked List Cycle II
- 【LeetCode 141】Linked List Cycle(Python)
- 【算法分析】如何理解快慢指针?判断linked list中是否有环、找到环的起始节点位置。以Leetcode 141. Linked List Cycle, 142. Linked List Cycle II 为例Python实现
- 【leetcode】Linked List Cycle (python)
- [leetcode]Linked List Cycle II @ Python
- Leetcode@python Linked List Cycle
- leetcode Linked List Cycle python
- Leetcode_linked-list-cycle(c++ and python version)
- 【leetcode】Linked List Cycle (python)
- leetcode 【 Linked List Cycle 】 python 实现
- Leetcode #141 Linked List Cycle Python
- leetcode Linked List Cycle II python
- LeetCode 141 — Linked List Cycle(C++ Java Python)
- 【LeetCode】【Python】Linked List Cycle
- [LeetCode]题解(python):141-Linked List Cycle
- 【LeetCode】Linked List Cycle 解题报告(Java & Python)
- [leetcode]Linked List Cycle @ Python