• 【数据结构】算法 Linked List Cycle find cycle begins 环形链表II [返回环的入口节点]


    Linked List Cycle find cycle begins 环形链表II [返回环的入口节点]

    双指针

    快慢指针,快指针一次移动2个node,慢指针一次移动1个node,

    通过公式推导的结论,当快慢指针在环内相遇到的节点开始继续使用指针依次遍历到环的入口的步数等于从头结点使用指针依次遍历到环入口的节点数

    /**
     * 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) {
            if(head==null){
                return null;
            }
            ListNode p = head; 
            ListNode q = head;
            if(q.next==null) return null;
            do{
                p = p.next;
                q = q.next.next;
            }while(p!=q&&q!=null&&q.next!=null);
    
            if(q==null||q.next==null){
                return null;//确定无环
            }        
            //确定存在环
            p = head;        
            while(p!=q){
                p = p.next;
                q = q.next;
            }
            return p;
        }
    }
    
  • 相关阅读:
    Html
    git和github简易教程
    Java基础
    如何学习一门语言
    leetcode题解(持续更新)
    浅谈安全威胁+引子
    内网渗透基础
    Java运算符
    Java修饰符
    Java变量类型
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14509108.html
Copyright © 2020-2023  润新知