zoukankan      html  css  js  c++  java
  • Go语言实现:【剑指offer】链表中环的入口结点

    ​该题目来源于牛客网《剑指offer》专题。

    给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

    Go语言实现:

    /**
     * Definition for singly-linked list.
     * type ListNode struct {
     *     Val int
     *     Next *ListNode
     * }
     */
     //哈希表
    func detectCycle(head *ListNode) *ListNode {
        //用map的key来判断是否已经存在
        m := make(map[*ListNode]int)
       
        //遍历链表,如果key不存在则赋值,已存在说明有环,遍历一遍后不存在则无环
        for head != nil {
            _, ok := m[head]
            if ok == false {
                m[head] = 1
                head = head.Next
            } else {
                return head
            }
        }
        
        return nil
    }
    
    //快慢指针
    func detectCycle(head *ListNode) *ListNode {
        if head == nil {
            return nil
        }
        
        //定义两个指针,fast一次走两步,slow一次走一步
        fast := head
        slow := head
        for {
            //fast遍历一遍,没有环
            if fast.Next == nil {
                return nil
            } 
            
            fast = fast.Next.Next
            slow = slow.Next
            //快慢相遇,存在环,跳出循环,注意此时并不一定是环入口结点
            if fast == slow {
                break
            }
        }
        
        //fast指向开始的地方,一次走一步,直到两者相遇
        fast = head
        for fast != slow {
            fast = fast.Next
            slow = slow.Next
        }
        
        return fast
    }
    
  • 相关阅读:
    springboot启动只显示图标不报错
    tmux常用
    ubuntu+anaconda+mxnet环境配置
    OpenCV学习笔记(二)
    c++基础
    c++算法实现(一)
    pytorch使用不完全文档
    ubuntu上传到百度网盘
    pickel加速caffe读图
    caffe常用
  • 原文地址:https://www.cnblogs.com/dubinyang/p/12099399.html
Copyright © 2011-2022 走看看