集合类

1.反转链表

1 <- 3 <- 5 <- 7 <- 9 转换为 1 <- 3 <- 5 <- 7 <- 9

现在有一个单链表,尝试将其所有节点倒序排列

public class Main {
    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(3);
        head.next.next = new Node(5);
        head.next.next.next = new Node(7);
        head.next.next.next.next = new Node(9);

        head = reverse(head);

        while (head != null){
            System.out.print(head.value+" ");
            head = head.next;
        }
    }

    public static class Node {
        public int value;
        public Node next;

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

    public static Node reverse(Node p) {
        //在这里实现
        if (p.next == null) return p;
        Node newHead = reverse(p.next);
        Node next = p.next;
        next.next = p;
        p.next = null;
        return newHead;
    }
}

重建二叉树

现在知道二叉树的前序: GDAFEMHZ,以及中序: ADEFGHMZ,请根据已知信息还原这颗二叉树
可得根节点值为:G,依次判断左右子树根节点;

posted @ 2022-05-12 22:31  学不会啊学不会  阅读(30)  评论(0)    收藏  举报