链表中环的入口结点

来源:互联网 发布:windows phone开发 编辑:程序博客网 时间:2024/05/26 07:27


Description:一个链表中包含环,请找出该链表的环的入口结点。


/* public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/public class Solution {    public ListNode EntryNodeOfLoop(ListNode head)    {        //先找碰撞点        ListNode slow = head;        ListNode fast = head;        while (fast != null && fast.next != null) {            slow = slow.next;            fast = fast.next.next;            if (slow == fast)                break;        }        if (fast == null || fast.next == null)            return null;        slow = head;        //碰撞点到入口点的距离=头结点到入口点的距离        while (slow != fast) {            slow = slow.next;            fast = fast.next;        }        return slow;    }}


原创粉丝点击