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);
        }
    }
}
相关推荐
逆向编程2 小时前
MATLAB高级数据结构:cell、struct与table深度应用
开发语言·数据结构·matlab
m0_6399069413 小时前
Redis入门|五种数据结构、使用场景、持久化RDB&AOF
数据结构·数据库·redis
2601_9707038317 小时前
工业除湿机租赁:把一份租金合同拆开看
大数据·数据结构·算法·数据库架构·推荐算法
丘山望岳1 天前
单调栈和单调队列
数据结构
UIU1141 天前
P16237 [蓝桥杯 2026 省 B] 应急布线
数据结构·c++·算法·蓝桥杯
Nuanyt1 天前
LeetCode Hot 100 链表专题2 3 题 (Java)
java·笔记·算法·leetcode·链表
黎相思1 天前
BTree
数据结构·b树·b+树
UIU1142 天前
P1233 [ICPC 2001 Taejon R] 木棍加工
数据结构·c++·算法·动态规划
niyongsheng2 天前
3D 装箱算法工程化:数据结构、放置启发式与支撑规则
数据结构·算法·rust