题目描述(难度:中等)
单链表有环指的是单链表中某个结点的 next 域指向的是链表中在它之前的某一个结点,这样在链表的尾部形成一个环形结构。如何判断单链表是否有环存在?(来源:阿里)
单链表结构
class LNode:
def __init__(self):
self.data = None # 数据域
self.next = None # 指针域
- 由于单链表中每个结点的地址都存储在其前驱结点的指针域中,因此,对单链表中任何一个结点的访问只能从链表的头指针开始进行遍历。
- 注意:在修改结点指针域的时候,记录下后继结点的地址,否则会丢失后继结点。
方法一:快慢指针
# 构造链表
def constructList():
i = 1
head = LNode()
head.next = None
cur = head
# 构造第一个链表
while i < 8:
tmp = LNode()
tmp.data = i
tmp.next = None
cur.next = tmp
cur = tmp
i += 1
cur.next = head.next.next.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
# first和second指针每次前移一步,当first==second时,此时指向的结点为入口点
while first != second:
first = first.next
second = second.next
return first
复杂度分析
- 时间复杂度为 O ( n ) O(n) O(n),只对链表进行一次遍历。
- 空间复杂度为 O ( 1 ) O(1) O(1),只需常量个指针变量来保存结点的地址信息。
主函数
if __name__ == "__main__":
head = constructList() # 头结点
meetNode = isLoop(head) # 指向fast==slow时的结点
loopNode = None
if meetNode != None:
print("有环")
loopNode = findLoopNode(head, meetNode)
print("环的入口点为:", loopNode.data)
else:
print("无环")
参考文献
[1] 何海涛. 剑指Offer:名企面试官精讲典型编程题(第2版). 北京: 电子工业出版社,2017
[2] 张波,楚秦. Python程序员面试算法宝典. 北京:机械工业出版社,2018