一、链表基础概念
(1)链表存储原理:
Python 链表
解析:head为头节点,data:存储数据区域,next:存放下一结点的引用
(2)判断链表是否有环:
思想:定义两个指针—一个慢的slow.next,一个快的fast.next.next;
两个指针同时从头部开始出发,如果相遇则有环,没有相遇,这没有环:
代码实现:

创建链表:

class Node(object):
def init(self,item):
self.item=item
self.next=None

def findloop(head):
slow=head
fast=head
loopexit=False
# 判断链表是否为空:
if head==None:
return False
# 判断链表是否有环:
while fast.next !=None and fast.next.next!=None:
slow=slow.next
fast=fast.next.next
if slow ==fast:
loopexit=True
break

找环的起始位置:

if loopexit:
    slow=head
    while slow !=fast:
        slow=slow.next
        fast=fast.next
    return slow.item
return False

相关文章:

  • 2021-08-06
  • 2022-01-15
  • 2021-08-26
  • 2021-09-16
  • 2021-06-03
  • 2022-12-23
  • 2021-11-24
  • 2022-01-15
猜你喜欢
  • 2021-06-14
  • 2021-08-20
  • 2022-12-23
  • 2022-01-16
  • 2022-02-16
相关资源
相似解决方案