栈的定义
栈(stack)是限制插入和删除只能在一个位置上进行的表,该位置是表的末端,叫做栈顶 (top)。它是后进先出(LIFO)的。
栈的基本操作
对栈的基本操作只有 push(进栈)和 pop(出栈)两种, 前者相当于插入,后者相当于删除最后的元素。
public class Stackdemo {
/*
* 入栈
* */
static void push(Stack<Integer> stack,int num){
stack.push(num);
System.out.println("push:"+num);
System.out.println("stack:"+stack);
}
/*
* 出栈
* */
static void pop(Stack<Integer> stack){
int num=stack.pop();
System.out.println("pop:"+num);
System.out.println("stack:"+stack);
}
public static void main(String[] args) {
Stack<Integer> stack=new Stack<>();
System.out.println("stack:"+stack);
System.out.println("empty:"+stack.empty());
push(stack,1);
push(stack,2);
pop(stack);
pop(stack);
push(stack,3);
push(stack,4);
pop(stack);
}
}
运行结构
stack:[]
empty:true
push:1
stack:[1]
push:2
stack:[1, 2]
pop:2
stack:[1]
pop:1
stack:[]
push:3
stack:[3]
push:4
stack:[3, 4]
pop:4
stack:[3]
栈的应用
栈的典型应用包括表达式求值、括号匹配等。