给你一个链表的头节点 head ,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。
方法一:哈希表
type ListNode struct {
Val int
Next *ListNode
}
func hasCycle(head *ListNode) bool {
L := head
hashMap := make(map[*ListNode]bool)
hashMap[L] = true
for L != nil {
if hashMap[L.Next] == true {
return true
}
hashMap[L.Next] = true
L = L.Next
}
return false
}
方法二:快慢指针
type ListNode struct {
Val int
Next *ListNode
}
func hasCycle(head *ListNode) bool {
if head == nil {
return false
}
for slow, fast := head, head;fast.Next != nil && fast.Next.Next != nil ;{
if slow.Next == fast.Next.Next {
return true
}
slow = slow.Next
fast = fast.Next.Next
}
return false
}