首页 > 编程语言 > 详细

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

时间:2021-03-10 08:38:55      阅读:23      评论:0      收藏:0      [点我收藏+]

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;
    }
}

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

原文:https://www.cnblogs.com/dreamtaker/p/14509108.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!