# 声明类结点
class LNode():
def __init__(self):
self.data = None # 数据域
self.next = None # 指针域
# 构造链表
def ConstructList():
head = LNode()
cur = head
i = 1
while i<8:
temp = LNode()
temp.data = i
cur.next = temp
cur = temp
i += 1
cur.next = head.next.next.next
# 输出带环的链表
# temp = head.next
# while temp!=None:
# print(temp.data)
# temp = temp.next
return head
# 判断单链表是否有环
def isLoop(head):
if head==None or head.next==None:
return None
# 初始时slow和fast都指向链表第一个结点
slow = head.next
fast = head.next
while fast!=None and fast.next!=None:
slow = slow.next
fast = fast.next.next
if slow==fast:
return slow
return None
# 找出环的入口点
def findLoopNode(head, meetNode):
first = head.next
second = meetNode
while first!=second:
first = first.next
second = second.next
return first
# 求环的长度
def LoopLength(first):
temp = first.next
len = 1
while temp!=first:
len += 1
temp = temp.next
return len
if __name__=="__main__":
head = ConstructList() # 获取链表头结点
meetNode = isLoop(head) # 得到相遇的结点
if meetNode!=None:
print("有环")
loopNode = findLoopNode(head, meetNode)
print("环的入口点为:"+str(loopNode.data))
else:
print("无环")
# 环的长度
len = LoopLength(loopNode)
print("环的长度为:"+str(len))