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

链表中环的入口结点

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

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

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

    public ListNode EntryNodeOfLoop(ListNode pHead) {
        if(pHead == null || pHead.next == null) {
            return null;
        }
        ListNode s = pHead, f = pHead.next;
        while(true) {
            if(f.next == null) {
                return null;
            }
            f = f.next;
            if(f == s) {
                break;
            }
            if(f.next == null) {
                return null;
            }
            f = f.next;
            if(f == s) {
                break;
            }
            s = s.next;
        }
        Set<ListNode> ring = new HashSet<>();
        ring.add(s);
        s = s.next;
        while(s != f) {
            ring.add(s);
            s = s.next;
        }
        while(true) {
            if(ring.contains(pHead)) {
                return pHead;
            }
            pHead = pHead.next;
        }
    }
}
全部评论

相关推荐

牛客51274894...:照片认真的吗,找个专门拍证件照的几十块钱整端正点吧,要不就别加照片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务