链表环和反转

Github

public class 链表环和反转 {
    public static int count;

    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        Node node6 = new Node(6);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
//        node6.next = node4;
//        System.out.println("链表是否有环" + isCore(node1));
//        System.out.println("链表环的长度" + count);
//        printLastNode(node1);
//        printLastNodeStack(node1);
    }

    public static class Node {
        int data;
        Node next;

        Node(int data) {
            this.data = data;
        }
    }

    /**
     * 判断链表是否有环 和环长
     *
     * @param head
     * @return
     */
    public static boolean isCore(Node head) {
        Node p1 = head;
        Node p2 = head;
        while (p2 != null && p2.next != null) {
            p1 = p1.next;
            p2 = p2.next.next;
            count++;
            //如果相等证明有环
            if (p1 == p2) {
                return true;
            }
        }
        return false;
    }


    /**
     * 递归反转链表
     *
     * @param node
     */
    public static void printLastNode(Node node) {
        if (node != null) {
            printLastNode(node.next);
            System.out.println("node = [" + node.data + "]");
        }
    }

    /**
     * 栈入出反转链表
     *
     * @param node
     */
    public static void printLastNodeStack(Node node) {
        //创建栈
        Stack stack = new Stack<>();
        //循环不为空入栈并取下一个节点继续
        while (node != null) {
            stack.push(node);
            node = node.next;
        }
        //出栈
        while (!stack.isEmpty()) {
            System.out.println("node = [" + stack.pop().data + "]");
        }
    }
}

你可能感兴趣的:(链表环和反转)