栈的要求是一个口负责进和出,先入后出的原则,插入和取出数据在一段完成的 ,一段为栈顶一段为栈底,删除正好相反。
使用场景:
- 子程序调用
- 递归处理
- 二叉树遍历
快速入门
- 使用数组模拟栈,栈是一个有序的列表,可以使用数组来存储数据内容。
- 实现思路:
(1) 使用数组类 模拟栈
(2)定义一个top来表示栈顶
(3)入栈,加入到top
(4)出栈
数组方式实现:
public class StackDemo {
private int maxSize;
private int arr[];
private int top = -1;
public StackDemo(int maxSize){
this.maxSize = maxSize;
arr = new int[maxSize];
}
public boolean isFull(){
return top == maxSize - 1;
}
public boolean isEmpty(){
return top == -1;
}
public void push(int num){
if (isFull()){
return;
}
top ++;
arr[top] = num;
}
public int pop(){
if (isEmpty()){
return -1;
}
top --;
return arr[top];
}
}
网友评论