Leetcode Golang 141. Linked List Cycle.go

版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/88992701

思路

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

code

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
}

更多内容请移步我的repo:https://github.com/anakin/golang-leetcode

猜你喜欢

转载自blog.csdn.net/anakinsun/article/details/88992701
今日推荐