栈的特征是后进先出(last-in, first-out, LIFO)。栈上的插入操作称为压入(PUSH),删除操作称为弹出(POP)。
下面使用一个数组S[n]来实现一个最多容纳n个元素的栈。定义一个属性指向最新插入的元素。栈的操作代码如下:
public class Stack { private Object[] objs; private int pointTop = -1; //指向最新插入的元素 public Stack() { } public Stack(int n) { //初始化数组的大小 objs = new Object[n]; } public boolean isEmpty() { if(pointTop == -1){ return true; } return false; } public boolean isFull() { if(pointTop == objs.length-1){ return true; } return false; } public boolean push(Object obj) { if(!isFull()){ pointTop += 1; objs[pointTop] = obj; return true; } return false; } public Object pop() { if(isEmpty()){ return -1; }else{ pointTop = pointTop-1; return objs[pointTop+1]; } } public static void main(String[] args) { Stack stack = new Stack(10); for(int i=0;i<5;i++){ if(stack.push(i)){ System.out.println(i); } } System.out.println(); for(int i=0;i<5;i++){ System.out.println(stack.pop()); } } }
运行结果:
0
1
2
3
4
4
3
2
1
0