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

链表中环的入口结点

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

相关推荐

不愿透露姓名的神秘牛友
07-08 13:15
点赞 评论 收藏
分享
frutiger:逆天,我家就安阳的,这hr咋能说3k的,你送外卖不比这工资高得多?还说大厂来的6k,打发叫花子的呢?这hr是怎么做到说昧良心的话的
找工作时遇到的神仙HR
点赞 评论 收藏
分享
05-20 21:57
已编辑
门头沟学院 Java
喜欢吃卤蛋的悲伤蛙在...:建信融通没消息吧,我2说有实习挂简历不理了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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