Leetcode-Linked List Cycle-Python
来源:互联网 发布:大富豪棋牌免费源码 编辑:程序博客网 时间:2024/06/04 00:37
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 = Noneclass 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
阅读全文
0 0
- Leetcode@python Linked List Cycle
- 【leetcode】Linked List Cycle (python)
- 【leetcode】Linked List Cycle (python)
- 【LeetCode】【Python】Linked List Cycle
- Leetcode-Linked List Cycle-Python
- [Leetcode][python]Linked List Cycle/Linked List Cycle II
- 【LeetCode with Python】 Linked List Cycle
- Leetcode #141 Linked List Cycle Python
- [Leetcode]142. Linked List Cycle II @python
- [leetcode: Python]141.Linked List Cycle
- leetcode Linked List Cycle & Linked List Cycle ||
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- [LeetCode]Linked List Cycle
- LeetCode | Linked List Cycle
- PHP new StdClass() 创建空对象
- 【面试集锦】好未来前端面试题---JS实现轮播图
- Cause: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Truncated incorr
- WIN10 简繁切换
- 神奇的C语言++运算符
- Leetcode-Linked List Cycle-Python
- JavaScript实现-截断字符串-Truncate a string
- 机器学习:支持向量机(SVM)与Python实现第(一)篇
- 数学建模(1)——遗传算法(GA)
- 关注国情民情,从身边做起
- uploadifive demo
- Ubuntu Server 命令行下显示中文乱码(菱形)解决办法
- DedeCMS:数据库密码和数据库连接失败解决方法
- hdu 6165 FFF at Valentine