算法系列——Linked List Cycle II

来源:互联网 发布:怎么找放单的淘宝商家 编辑:程序博客网 时间:2024/05/25 12:21

题目描述

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

解题思路

找到环的入口结点。这是链表问题中的一个经典问题。

比较简单的方法,是先用快慢双指针找到重合位置。然后慢指针从头开始,和快指针 均采用一步速开始遍历,重合位置为环的入口结点。

具体分析可以看这篇博客。
http://www.cnblogs.com/hiddenfox/p/3408931.html

程序实现

public class Solution {    public ListNode detectCycle(ListNode head) {        if(head==null||head.next==null)            return null;        ListNode p1=head;        ListNode p2=head;        while(p2!=null&&p2.next!=null){            p1=p1.next;            p2=p2.next.next;            if(p1==p2)                break;        }        //p1 从起始位置开始,和p2         if(p1==p2){            p1=head;            while(p1!=p2){                p1=p1.next;                p2=p2.next;            }            return p1;       }        else           return null;    }}
原创粉丝点击