本文实例讲述了Python3实现的判断环形链表算法。分享给大家供大家参考,具体如下:
给定一个链表,判断链表中是否有环。
方案一:快慢指针遍历,若出现相等的情况,说明有环
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
# 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
"""
slow = fast = head
while fast and fast. next :
slow = slow. next
fast = fast. next . next
if fast = = slow:
return True
return False
|
方案二:遍历链表,寻找.next=head的元素。 但超出时间限制
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# 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 not head:
return False
cur = head. next
while cur:
if cur. next = = head:
return True
cur = cur. next
return False
|
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/zhenghaitian/article/details/81025412