zoukankan      html  css  js  c++  java
  • 算法-找出链表环的入口节点

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
    核心思路(其实就是佛罗伊德算法): 先根据快慢指针算法找到快慢指针能相遇的最短路程差。
          然后重置快慢指针
          先让快指针走上面得到的路程差
         在让快慢指针一起走,当慢指针和快指针相遇时即是环的入口位置

        
    */ public class Solution { public ListNode detectCycle(ListNode head) { // 如果链表为空或者单节点无环,直接返回null if(head == null || head.next == null){ return null; } // 快慢指针,借鉴是否有环的算法找出来两者能相遇的最小路程差:stepCount ListNode slow = head; ListNode fast = head.next; int stepCount = 0; while(fast != slow){ if(fast == null || fast.next == null){ return null; } fast = fast.next.next; slow = slow.next; stepCount ++; } slow = head; fast = head.next; // fast先走路程差 for(int i = 0; i < stepCount; i ++){ fast = fast.next; } // 当slow和fast相遇时即是环的开始位置 while(fast != slow){ slow = slow.next; fast = fast.next; } return slow; } }
  • 相关阅读:
    Wx-小程序-使用canvas截图保存
    Wx-小程序-图片预览、保存
    CSS-文本溢出省略号表示
    Wx-小程序-长按复制文本
    Vue-组件通信
    JS-禁用浏览器前进后退
    JS-内置对象和方法
    JS-冒泡排序
    JS-常用方法合集
    Wx-小程序-组件式开发之Vant
  • 原文地址:https://www.cnblogs.com/caiyao/p/12985589.html
Copyright © 2011-2022 走看看