'''
leetcode 141. 环形链表
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。
如果 pos 是 -1,则在该链表中没有环。
与链表有关的算法题通常会用到双指针或快慢指针
每迭代一次,快指针faster向前走两步,慢指针slow向前走一步
如果链表中不包含环状结构,则快指针一定比慢指针先到达链表的尾部
否则,快指针和慢指针将一定在某个时刻指向相同的节点
'''
# 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 head is None:
return False
if head.next is None:
return False
slow=head
faster=head
while(1):
if faster.next is None:# 如果faster指针走到了链表的末尾,则证明链表中一定不包含环状结构
return False
else:
slow=slow.next
i=2
while(i>0 and faster):
faster=faster.next
i-=1
if faster is None:
return False
if faster==slow:
return True
if __name__=="__main__":
node_3=ListNode(3)
node_2=ListNode(2)
node_0=ListNode(0)
node_4=ListNode(-4)
node_3.next=node_2
node_2.next=node_0
node_0.next=node_4
node_4.next=node_2
print(Solution().hasCycle(node_3))