P4104.环形链表判断

题目

https://codefun2000.com/ide/P4104?pset=zijie

思路

https://sprintzerzz.github.io/algorithm-visualization/codefun2000/P4104-Linked-List-Cycle/

code(ACM)

java 复制代码
import java.util.*;

class Main {

    static class Node {
        int value;
        Node next;

        Node(int value) {
            this.value = value;
        }
    }

    static Node detectCycle(Node head) {
        Node slow = head;
        Node fast = head;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

            // 相遇说明有环
            if (slow == fast) {
                slow = head;

                while (slow != fast) {
                    slow = slow.next;
                    fast = fast.next;
                }

                return slow;
            }
        }

        return null;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        // 构造链表
        Node dummy = new Node(-1);
        Node tail = dummy;

        for (int i = 0; i < n; i++) {
            Node cur = new Node(sc.nextInt());
            tail.next = cur;
            tail = cur;
        }

        // 读取入环位置
        int pos = sc.nextInt();

        // 只有 pos != -1 才构造环
        if (pos != -1) {
            Node cur = dummy.next;

            for (int i = 0; i < pos; i++) {
                cur = cur.next;
            }

            tail.next = cur;
        }

        // 判断是否有环
        Node cycle = detectCycle(dummy.next);

        if (cycle == null) {
            System.out.print(-1);
        } else {
            // 寻找入环节点下标
            Node cur = dummy.next;
            int index = 0;

            while (cur != cycle) {
                cur = cur.next;
                index++;
            }

            System.out.print(index);
        }
    }
}
相关推荐
郝学胜-神的一滴1 小时前
Effective Python 条款36:优雅拼装迭代器与生成器
开发语言·数据结构·人工智能·python·numpy·scikit-learn
console.log('npc')6 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
LK_071 天前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
FR02EN7771 天前
[LeetCode] 26、80.删除有序数组中的重复项 题解
数据结构·算法
H.莓飛2 天前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
饮水桶_T2 天前
Python 面向对象(十七)|继承、封装、多态 笔记
数据结构·笔记·算法
风落青芜2 天前
链式二叉树的实现与基本操作
c语言·开发语言·数据结构·算法
wo_jack2 天前
C++ 入门笔记(十八):list 进阶 —— const 迭代器、operator-> 与 clear 的坑
数据结构·c++·面试·stl·list
ashiho3 天前
【LeetCode hot 100】3. 无重复字符的最长子串 (三种解法)
java·数据结构·后端·算法·leetcode·滑动窗口