自学内容网 自学内容网

lc 141 环形链表ACM模式

双指针fast 和slow

slow一次走一步

fast一次走两步

快慢指针相等则代表有环

import java.util.Scanner;

public class huanlian {
    public static boolean hasCycle(ListNode head) {
        if(head == null || head.next == null) return false;
        ListNode fast = head;
        ListNode slow = head;
        while(fast.next != null && fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;

            if(fast == slow){
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt(); // 读取节点数量
        ListNode head = null, tail = null;

        for (int i = 0; i < n; i++) {
            int val = scanner.nextInt();
            ListNode newNode = new ListNode(val);
            if (i == 0) {
                head = newNode;
                tail = newNode;
            } else {
                tail.next = newNode;
                tail = newNode;
            }
        }

        // 读取环的信息,pos为-1表示无环
        int pos = scanner.nextInt();
        if (pos != -1 && pos < n) {
            // 创建环
            ListNode cur = head;
            while(pos-- > 0){
                cur = cur.next;
            }
            tail.next = cur; // 假设pos为环的起始节点索引
        }
        boolean result = hasCycle(head);
        System.out.println(result ? "True" : "False");

        scanner.close();
    }
}

原文地址:https://blog.csdn.net/m0_51351957/article/details/143508869

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!