zoukankan      html  css  js  c++  java
  • 环形链表(给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null)

    思想:

    思想:用快慢指针先判断是否有环,有环则
    假设头结点到环入口距离为n,环入口到快慢指针相遇结点距离为m,则慢指针走的路程
    为m+n,而快指针走的路程为m+n+k*l (k*l表示绕环走的路程),我们知道快指针路程是慢指针
    路程二倍,则k*l = m+n;
    找到相遇结点后,让快指针指向头结点,然后让快慢指针都向后移动,当快指针向后移动n次时,就找到
    了环入口,

    代码实现如下:

    public ListNode detectCycle(ListNode head) {
            if(head == null || head.next == null) return null;
            ListNode f = head;
            ListNode s = head;
            //判断是否有环
            while(f != null && f.next!=null){
                f = f.next.next;
                s = s.next;
                if(f == s){
                    break;
                }
                
            }
            //没有环,直接返回
            if(f!=s) return null;
            //让快指针指向头结点,
            f = head;
            //下次快慢结点相等时就是环入口
            while(f!=s){
                f = f.next;
                s = s.next;
            }
            return f;
        }
  • 相关阅读:
    Git远程操作
    696. Count Binary Substrings
    693. Binary Number with Alternating Bits
    821. Shortest Distance to a Character
    345. Reverse Vowels of a String
    89. Gray Code
    数组操作符重载
    C++字符串反转
    马克思的两面性-来自网友
    C++字符串
  • 原文地址:https://www.cnblogs.com/du001011/p/10634328.html
Copyright © 2011-2022 走看看