找出链表是否是环状链表,并找出对应的入口

1.定义Node属性

package com.example.demo;

public class Node1 {
    // 这仅仅是一个标识,用来标记这是哪一个节点
    public int tag;

    public Node next;

    public Node(Node next, int tag) {
        this.next = next;
        this.tag = tag;
    }
}

2.构建有环链表

    0public static Node1 createTestNode() {
        Node1 node13 = new Node(null, 13);
        Node1 node12 = new Node(node13, 12);
        Node1 node11 = new Node(node12, 11);
        Node1 node10 = new Node(node11, 10);
        Node1 node9 = new Node(node10, 9);
        Node1 node8 = new Node(node9, 8);
        Node1 node7 = new Node(node8, 7);
        Node1 node6 = new Node(node7, 6);
        Node1 node5 = new Node(node6, 5);
        Node1 node4 = new Node(node5, 4);
        Node1 node3 = new Node(node4, 3);
        Node1 node2 = new Node(node3, 2);
        // 设置环入口
        node13.next = node5;
        Node1 head = new Node(node2, 1);
        return head;
    }

 3.判断是否是有环链表,并找出对应的入口

package com.example.demo;

public class LinkedIsRing {
    //快慢指针判断链表是否有环,并找出环的起始节点
    public static Node1 isCircleBySlowFast(Node node) {
        Node slow = node;
        Node fast = node;
        Node p = node;
        while (slow != null && fast.next !=null) {
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast) {
                Node q = fast;
                while (p != q) {
                    p = p.next;
                    q = q.next;
                }
                return p;
            }
        }
        return null;
    }
}

 

 

你可能感兴趣的:(算法,leetcode)