zoukankan      html  css  js  c++  java
  • 环状链表的入环节点

    快指针每次走两步。慢指针每次走一步。
    相遇的时候 肯定在环中。

    这个时候最简单的办法就是在围绕环来一圈 算出count。
    求出了环的大小n

    这个时候两个都从起点开始。一个先走n,另一个再开始走。相遇在入口

    下面是一种比较简单的写法,但是不是很好理解。 假设快的比满的只多走了一圈 很好解释。 如果是多圈呢? 就需要严谨的数学证明了

    /**
     * Definition for ListNode.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int val) {
     *         this.val = val;
     *         this.next = null;
     *     }
     * }
     */
    
    
    public class Solution {
        /*
         * @param head: The first node of linked list.
         * @return: The node where the cycle begins. if there is no cycle, return null
         */
        public ListNode detectCycle(ListNode head) {
            // write your code here
            ListNode slow = head;
            ListNode fast = head;
            if(head == null||head.next == null){
                return null;
            }
            if(head.next.next == head){
                return head;
            }
            while(fast.next !=null&&slow.next != null){
                if(fast.next.next == null){
                    return null;
                }
                slow = slow.next;
                fast = fast.next.next;
                if(slow == fast){
                    ListNode slownew = fast;
                    ListNode fastnew = head;
                    while(slownew!=fastnew){
                        slownew = slownew.next;
                        fastnew = fastnew.next;
                    }
                    return fastnew;
                }
            }
            return null;
        }
    }
  • 相关阅读:
    vue中 key 值的作用
    v-on可以监听多个方法吗?
    vue常用的修饰符
    v-if和v-show的区别
    Vue和其他框架的区别
    Vue面试题总结——目录
    vue是一个渐进式的框架,我是这么理解的
    原生JS封装创建多级菜单函数
    如何使用mongodb(建立原型,连接数据库)
    Hive 的安装与配置
  • 原文地址:https://www.cnblogs.com/tobemaster/p/7914655.html
Copyright © 2011-2022 走看看