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

链表中环的入口节点

http://www.nowcoder.com/practice/6e630519bf86480296d0f1c868d425ad

题目需要找到链表中环的第一个节点,设置快慢指针遍历该链表,当快慢指针相遇说明有环,然后再遍历一次,找入口节点。

/**
 * Definition for singly-linked list.
 * class ListNode {
 * int val;
 * ListNode next;
 * ListNode(int x) {
 * val = x;
 * next = null;
 * }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }
        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;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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