环形链表
判断是否有环
集合法
想法:用集合。遍历时将元素放进集合中,如果有环一定发生重复。
难点:想到了集合,没想到结点能直接放进去。
def hasCycle(self, head):
s=set()
while head:
if head in s:
return True
s.add(head)
head=head.next
return False
快慢指针法
想法: 快指针走两步,慢指针走一步,如果无环,快指针会走到表尾,否则快慢指针一定会相遇
难点:想到了快慢指针,有进步!但是没想到他俩一定会相遇
def hasCycle(self, head):
if head is None or head.next is None:
return False
fast,slow=head,head
while fast and fast.next:
fast=fast.next.next
slow=slow.next
if fast==slow:
return True
return False
环的位置
相遇后让fast指针指向head,发现a为c或者c加上圆环的倍数,也就是说,当fast与slow同步移动时,slow必定会在入口处与fast相遇。
def hasCycle(self, head):
fast,slow=head,head
while True:
if not (fast and fast.next): return
fast,slow=fast.next.next,slow.next
if fast==slow:break
fast=head
while fast!=slow:
fast,slow=fast.next,slow.next
return fast