题解 | #判断链表中是否有环#

判断链表中是否有环

https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9

/**
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */
object Solution {
    /**
    * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
    *
    * 
        * @param head ListNode类 
        * @return bool布尔型
    */
    fun hasCycle(head: ListNode?): Boolean  {
        // write code here
        
        val mHead = ListNode(-1)
        mHead.next = head

        var current: ListNode? = mHead
        var arrow = current?.next

        val step = 4
        while (arrow != null && current != null) {
            repeat(step) {
                if (arrow == current) {
                    return true
                }
                arrow = arrow?.next
                if (arrow == null) {
                    return false
                }
            }
            current = current.next
        }
        return false
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务