赞
踩
牛客面试必刷101题—— 判断链表中是否有环
牛客面试必刷101题—— 链表中环的入口结点
package main import . "nc_tools" /* * type ListNode struct{ * Val int * Next *ListNode * } */ /** * * @param head ListNode类 * @return bool布尔型 */ func hasCycle(head *ListNode) bool { if head == nil || head.Next == nil { return false } slow := head fast := head.Next for slow != fast { if fast == nil || fast.Next == nil { return false } fast = fast.Next.Next slow = slow.Next } return true }
package main func EntryNodeOfLoop(head *ListNode) *ListNode { slow := head fast := head for fast != nil && fast.Next != nil { slow = slow.Next fast = fast.Next.Next if slow == fast { fast = head for slow != fast { slow = slow.Next fast = fast.Next } return slow } } return nil }
今天的解题算法主要使用了双指针这一算法,我们利用定义快慢指针来判断链表中是否有环以及环的节点,这里的理论依据主要是floyd判圈算法,大家有兴趣的化可以看一下文末的文章来理解一下该算法,这里就不做赘述了
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。