Java数据结构的热点问题

2020-03-08  本文已影响0人  今天也要努力呀y

1.对Java堆栈的理解

JVM内存中两个重要的空间,一种栈内存,一种堆内存

public class Stack {
    int data[];
    int top;
    int maxsize;

    public Stack(int maxsize) {
        this.maxsize = maxsize;
        data = new int[maxsize];
        top = -1;
    }

    public boolean push(int data){
        if (top + 1 == maxsize){
            System.out.println("栈已满");
            return false;
        }
        this.data[++top] = data;
        return true;
    }
    public int pop() throws Exception {
        if (top == -1){
            throw new Exception("栈已空");
        }
        return data[top--];
    }

    public static void main(String[] args) throws Exception {
        Stack stack = new Stack(1000);
        stack.push(1);
        stack.push(2);
        while (stack.top>=0){
            System.out.println(stack.pop());
        }
    }
}

2.如何遍历二叉树

三种遍历方式
1.先序:
2.中序:
3.后序:

public void PreOrder(Node node) {
        if (node == null) {
            return;
        } else {
            System.out.println(node.getData());
            node.getLchild();
            node.getRchild();
        }
    }

    public void Inorder(Node node) {
        if (node == null) {
            return;
        } else {
            node.getLchild();
            System.out.println(node.getData());
            node.getRchild();
        }
    }

    public void PostOrder(Node node) {
        if (node == null) {
            return;
        }else {
            node.getLchild();
            node.getRchild();
            System.out.println(node.getData());
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读