核心思想:
说到栈,我们就会想到“先进后出,后进先出”,它只允许访问一个数据项,也就是最后插入的数据项,只有移除这个数据项,才能访问倒数第二个插入的数据项;
如何实现栈:
<span style="font-size:18px;">public class MyStack {
//栈的最大容量
private int maxSize;
//栈里面存放的long类型的数组
private long[] arr;
//指向栈顶的元素
private int top;
// 构造方法(初始化栈)
public MyStack(int size) {
maxSize = size;
arr = new long[maxSize];
//刚开始是没有数据的
top = -1;
}
// 压入数据
public void push(long value){
++top;
arr[top]=value;
}
// 弹出数据
public long pop() {
return arr[top];
top--;
}
// 访问栈顶元素
public long peek() {
return arr[top];
}
// 栈是否为空
public boolean isEmpty() {
return (top == -1);
}
// 栈是否满了
public boolean isFull() {
//top是从0开始的++
return (top == maxSize - 1);
}
}</span>
<span style="font-size:18px;">public class TestStack {
public static void main(String[] args) {
MyStack ms = new MyStack(10);
ms.push(40);
ms.push(30);
ms.push(20);
ms.push(10);
ms.push(-10);
ms.push(-20);
while(!ms.isEmpty()){
System.out.println(ms.pop());
}
}
}</span>