判断链表是否有环
class Node:
def __init__(self,data=None):
self.data=data
self.next=None
class ListNode:
def __init__(self):
self.head=Node()
def append(self,num):
node=Node(num)
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next=node
@property
def lastNode(self):
cur=self.head
while cur.next!=None:
cur=cur.next
return cur
def print(self):
cur=self.head
while cur.next!=None:
print('data:',cur.data)
cur=cur.next
print('end:',cur.data)
def judge_circle(self):
slow=self.head.next
fast=self.head.next
while fast!=None and fast.next!=None:
slow=slow.next
fast=fast.next.next
if slow==fast:
print('链表有环')
return
print('链表无环')
if __name__ == '__main__':
list=ListNode()
for i in range(1,10):
list.append(i)
list.lastNode.next=list.head.next.next
list.judge_circle()

© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
喜欢就支持一下吧