题解 | #链表中环的入口结点#

链表中环的入口结点

http://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4

/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {

    public ListNode EntryNodeOfLoop(ListNode pHead) {
        // 头结点和相遇点 距离 入口的步数相同
        ListNode meetNode = findMeetNode(pHead);
        if(meetNode == null){ return null;}
        ListNode start = pHead;
        while(start != meetNode){
            start = start.next;
            meetNode = meetNode.next;
        }
        return start;
    }

    public ListNode findMeetNode(ListNode pHead){
        ListNode fast = pHead,slow = pHead ;
        while(fast != null && fast.next != null){
            fast = fast.next.next ;
            slow = slow.next ;
            if(slow == fast){
                return slow ;
            }
        }
        return null;
    }
}
全部评论

相关推荐

废铁汽车人:秋招真是牛鬼蛇神齐聚一堂
点赞 评论 收藏
分享
喜欢走神的孤勇者练习时长两年半:池是池,发是发,我曾池,我现黑
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务