您的位置:首页 > 编程语言 > Python开发

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息