什么是栈
栈,是一种抽象数据类型,只允许在有序的线性数据集合的一端进行加入数据和移除数据的运算。因而按照后进先出(LIFO, Last In First Out)的原理运作。
基本操作
- 入栈(push):将数据放入栈的顶端,新数据成为栈顶元素。
- 出栈(pop):将栈顶元素在栈中移除,下一个元素成为新的栈顶元素。
基本特点
知道了栈的基本原理我们得出栈的两个特点:
- 先进后出,后进先出。
- 除头尾节点之外,每个元素有一个前驱,一个后继。
Java语言实现
核心类:
public class MyStack {
//栈的底层使用数组存储数据
int[] stack;
public MyStack() {
stack = new int[0];//初始化
}
//将元素压入到栈中(入栈操作)
public void push(int element){
int[] newStack = new int[stack.length + 1];
System.arraycopy(stack,0,newStack,1,stack.length);
newStack[0] = element;
stack = newStack;
}
//取除栈顶元素(出栈操作)
public int pop(){
if (stack.length == 0){
throw new RuntimeException("当前栈为空,无法进行出栈操作");
}
int element = stack[0];
int[] newStack = new int[stack.length - 1];
System.arraycopy(stack,1,newStack,0,stack.length - 1);
stack = newStack;
return element;
}
//查看栈顶元素
public int pick(){
if (stack.length == 0){
throw new RuntimeException("当前栈为空");
}
return stack[0];
}
}
测试类:
public class StackTest {
public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
System.out.println(stack.pop()+"出栈");
stack.push(3);
stack.push(4);
System.out.println(stack.pop()+"出栈");
System.out.println(stack.pop()+"出栈");
System.out.println(stack.pop()+"出栈");
}
}
测试结果:
2出栈
4出栈
3出栈
1出栈