defexit_loop(head):#定义两个指针
fast=slow=head
while fast.next.nextand slow,next:
fast=fast.next.next
slow=slow.nextif fast==slow:returnTruereturnFalse
寻找环的起点:两指针一个从起点出发,一个指针从第一次相遇点出发,两指针再次相遇点即为环的起点
defstart_loop(head):
fast=slow=head
while fast.next.nextand slow.next:
fast=fast.next.next
slow=slow.next#找到第一次相遇点if fast==slow:break#一个指针从起点出发,另一个从相遇点出发
fast=head
while fast.nextand slow.next:
fast,slow=fast.next,slow.nextif fast==slow:return slow.val
3.移除链表中的节点
1)移除链表中的指定节点
defremove_node(head,val):ifnot head:return head
if head.val==val:return head.next
pre,cur=head,head.next#找到删除节点的位置(cur指针所指的位置)while cur and cur.val!=val:
pre,cur=pre.next,cur.next#在遍历链表结束前,找到删除位置if cur:
pre.next=cur.nextreturn head
2)移除顺序链表中的重复节点
defremove_repeat(head):ifnot head:return head
pre,post=head,head.nextwhile post:#若两指针节点值相等,删除if pre.val==post.val:
pre.next=post.next
post=post.next#不相等,两指针分别后移else:
pre,post=pre.next,post.nextreturn head