Leetcode Golang 141. Linked List Cycle.go

2019-04-12 10:41:11 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412854

思路

快慢指针,如果相遇则有环

code

代码语言:javascript复制
func hasCycle(head *ListNode) bool {
	if head == nil {
		return false
	}
	fast := head.Next
	slow := head

	for slow != nil && fast != nil && fast.Next != nil {
		slow = slow.Next
		fast = fast.Next.Next
		if fast == slow {
			return true
		}
	}
	return false
}

0 人点赞