什么是栈
什么是Java虚拟机栈从数据结构的角度出发,栈其实就是一种数据结构,特点:先进后出
中缀表达式Java虚拟机栈就是存放在内存当中的一块内存
此时JVM stack(Java虚拟机栈),只是JVM当中的一块内存,该内存一般用来存放
例如:局部变量........
调用函数的时候,我们会为这个函数开辟一块内存,叫做栈帧.在哪里开辟呢?
JVM stack
后缀表达式像我们平时写到的表达式一般都是中缀表达式
举例:
(5 + 4)*3-2
如何计算后缀表达式中缀表达式转后缀表达式
第一步:表达式加括号
(5 + 4)*3-2
((5 + 4)*3)-2
(((5 + 4)*3)-2)
后缀表达式指的是把这个运算符放到某个表达式的后边
第二步:把运算符挪到括号的后面
(((5 4)+3)*2)-
第三步:去掉括号
54+3*2-
这就是一个后缀表达式
前缀表达式同理,把运算符挪到括号的前面
Java当中栈的方法
push:入栈public class TesDome2 { public static void main(String[] args) { Stackstack = new Stack<>(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); System.out.println(stack); } } 打印结果:
画图表示:
pop:弹出栈顶元素;并且删除public class TesDome2 { public static void main(String[] args) { Stackstack = new Stack<>(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); System.out.println(stack.pop());//弹出栈顶元素;并且删除 } } 打印结果;
pop会把栈顶的4弹出,并且删除
peek:获取栈顶元素,不删除public class TesDome2 { public static void main(String[] args) { Stackstack = new Stack<>(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); System.out.println(stack.peek());//获取栈顶元素,不删除 } } 打印结果:
empty:判断栈里为不为空实现一个简单栈public class TesDome2 { public static void main(String[] args) { Stackstack = new Stack<>(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); System.out.println(stack.empty()); } } 打印结果:
栈的底层也是一个数组
class MyStack{ private int[] elem; private int usedSize; public MyStack(){ this.elem = new int[5]; } public void push(int val){ if(Full()){ //扩容 this.elem = Arrays.copyOf(this.elem,2*this.elem.length); } this.elem[this.usedSize] = val; this.usedSize++; } //判断数组满不满 public boolean Full(){ return this.usedSize == this.elem.length; } public int pop(){ if(isEmpty()){ throw new RuntimeException("栈为空 !"); } int oldVal = this.elem[usedSize-1]; this.usedSize--; return oldVal; } public int peek(){ if(isEmpty()){ throw new RuntimeException("栈为空 !"); } return this.elem[usedSize-1]; } public boolean isEmpty(){ return this.usedSize == 0; } }



