Java环形链表 II

1.题目

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。环形链表 II
说明:不允许修改给定的链表。

2.分析

定义两个引用:fast和slow,开始fast走的速度为slow的两倍,
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3.代码

 //给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
    public ListNode detectCycle(ListNode head) {
    
    
        if (head == null) return null;
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
    
    
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
    
    
                break;
            }
        }
        if (fast == null || fast.next == null) {
    
    
            return null;
        }
        fast = head;
        while (fast != slow) {
    
    
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
测试:
 public static void main(String[] args) {
    
    
        MyLinkedList myLinkedList = new MyLinkedList();
        myLinkedList.addLast(12);
        myLinkedList.addLast(23);
        myLinkedList.addLast(34);
        myLinkedList.addLast(45);
        myLinkedList.addLast(56);
        System.out.println("myLinkedList:");
        myLinkedList.display();
        myLinkedList.createLoop();
        ListNode ret = myLinkedList.detectCycle();
        System.out.println(ret.val);
    }

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44721738/article/details/121192597