判断链表是否有环,并返回链表的第一个节点

class Solution {

    private static ListNode function(ListNode head) {
        if (head == null || head.next == null || head.next.next == null) {
            return null;
        }
        ListNode slow = head.next;
        ListNode fast = head.next.next;

        while (slow != fast) {
            slow = slow.next;
            if (fast.next == null || fast.next.next == null) {
                return null;
            }
            fast = fast.next.next;
        }

        fast = head;

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

        return fast;
    }

    private static void print(ListNode head) {
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }

    private static void printEle(ListNode node) {
        if (node == null) {
            System.out.println("null");
        } else {
            System.out.println(node.val);
        }
    }

    public static void main(String[] args) {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
//        n5.next = n2;

        ListNode head = function(n1);

        printEle(head);


//        print(head);

    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}


猜你喜欢

转载自blog.51cto.com/tianyiya/2335295