栈(Stack):一种特殊的 线性表,其只允许在固定的一端(栈顶)进行插入和删除元素操作(另一端为栈底)。栈中的数据元素遵循先进后出(LIFO)的原则。
- 栈的基本方法
1.public stack();创建栈
2. public E push(); 入栈
3. public E pop(); 出栈(删除栈顶元素)
4. public E peek()查看栈顶元素(不删除)
5. public boolean empty(); 判断栈是否为空
- 手动实现栈(数组)
public class MyStack{
private int usedSize;
private int []elem;
public MyStack(){
this.elem=new int[10];
}
public boolean isFull(){
return this.usedSize==elem.length;
}
public int push(int value){
if(isFull()){
throw new RuntimeException("栈已满!");
}
this.elem[this.usedSize]=value;
this.usedSize++;
return this.elem[this.usedSize-1];
}
//弹出栈顶元素
public int pop() {
if(empty()){
throw new RuntimeException();
}
this.usedSize--;
return this.elem[usedSize];
}
//peek拿到栈顶元素不删除
public int peek() {
if(empty()){
throw new RuntimeException();
}
return this.elem[usedSize-1];
}
public boolean empty(){
return this.usedSize == 0;
}
public int size(){
return this.usedSize;
}
//测试
public static void main(String[] args) {
MyStack myStack = new MyStack();
myStack.push(2);
myStack.push(6);
myStack.push(9);
myStack.push(1);
System.out.println(myStack.peek());
System.out.println(myStack.pop());
System.out.println(myStack.peek());
System.out.println(myStack.size());
System.out.println(myStack.empty());
}
}
- 测试结果:
问题:中缀表达式转换成后缀表达式(逆波兰式)
自己总结的:运算数加括号,将运算符从离他最近的括号中提取出来。将操作数依次入栈,遇到运算符从栈中取出操作数作为右操作数,再取出一个数作为左操作数,将运算结果入栈。走完即可得到运算结果。