环形链表

11 阅读1分钟

环形链表

思路一:记录遍历过的链表的所有地址,看下一个节点的地址是否在这里出现过

采用切片存

func hasCycle(head *ListNode) bool {
	var slice []*ListNode
	node := head
	for node != nil {
		//判断切片中是否存在
		for _, item := range slice {
			if item == node {
				return true
			}
		}
		slice = append(slice, node)
		node = node.Next
	}
	return false
}

采用 map存

func hasCycle(head *ListNode) bool {
	myMap:=make(map[*ListNode]int)
	node := head
	for node != nil {
		//判断切片中是否存在
		if _,ok:=myMap[node];ok{
			return true
		}
		myMap[node]=1
		node = node.Next
	}
	return false
}

快慢指针法:

快指针移动两步,慢指针移动一步

func hasCycle(head *ListNode) bool {
	if head==nil || head.Next==nil{
		return false
	}
	slow:=head
	fast:=head.Next
	for fast!=slow{
		if fast==nil || fast.Next==nil{
			return false
		}
		slow=slow.Next
		fast=fast.Next.Next
	}
	return true
}