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

链表中环的入口结点

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;
    }
}
全部评论

相关推荐

三年之期已到我的offer快到碗里来:9硕都比不上9本
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务