Java 中 栈结构的三种使用方式 最后一种效率最高

 

1. 最不推荐

LinkedList<Integer> stack1 = new LinkedList<>();
stack1.addLast(1);
stack1.addLast(2);
stack1.addLast(3);

while (!stack1.isEmpty()) {
System.out.println(stack1.pollLast());
}
System.out.println("=======");


2. Java 默认
Stack<Integer> stack = new Stack<>();
stack.add(1);
stack.add(2);
stack.add(3);

while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
System.out.println("=======");


3. 如果能确定压栈数量,最优解
int[] stack2 = new int[3];
int index = 0;
stack2[index++] = 1;
stack2[index++] = 2;
stack2[index++] = 3;

while (stack2 != null && index == 0) {
System.out.println(stack2[--index]);
}
posted @ 2023-03-18 18:44  Minde  阅读(55)  评论(0编辑  收藏  举报