java顺序栈功能通过数组实现
1.定义栈接口
1 public interface Stack<T> { 2 //返回栈的大小 3 public int size(); 4 //判断栈是否为空 5 public boolean isEmpty(); 6 //入栈 7 public void push(T t); 8 //出栈 9 public Object pop() throws StackEmptyException; 10 //返回栈顶元素 11 public Object peek() throws StackEmptyException ; 12 }
2.自定义异常
1 public class StackEmptyException extends RuntimeException { 2 //新增栈为空的异常类 3 public StackEmptyException(String eMeaasge ){ 4 super(eMeaasge); 5 } 6 }
3.数组实现栈接口
1 public class StackArray<T> implements Stack<T> { 2 //栈的初始容量为2; 3 private final int LEN=2; 4 // 定义栈的指针; 5 private int top; 6 // 栈以数组实现 7 private T[] elements; 8 // 构造方法进行初始化 9 public StackArray(){ 10 top=-1; 11 elements= (T[]) new Object[LEN]; 12 } 13 14 @Override 15 public int size() { 16 return top+1; 17 } 18 19 @Override 20 public boolean isEmpty() { 21 return top<0; 22 } 23 24 @Override 25 public void push(T t) { 26 if(this.size()==elements.length){ 27 this.expandSize(); 28 } 29 // ++top,先自增,再赋值 30 elements[++top]=t; 31 } 32 33 @Override 34 public Object pop() throws StackEmptyException { 35 if(this.isEmpty()){ 36 throw new StackEmptyException("当前栈为空,无法出栈"); 37 } 38 Object obj = elements[top]; 39 // top--,先赋值,再自减 40 elements[top--]=null; 41 return obj ; 42 } 43 44 @Override 45 public Object peek() throws StackEmptyException { 46 if(this.isEmpty()){ 47 throw new StackEmptyException("当前栈为空,无内容"); 48 } 49 return elements[top]; 50 } 51 //栈容量扩容 52 public void expandSize(){ 53 T[] a= (T[]) new Object[elements.length *2]; 54 for(int i=0;i<elements.length;i++){ 55 a[i]=elements[i]; 56 } 57 elements=a; 58 } 59 }
4.测试
1 public class Main { 2 3 public static void main(String[] args) { 4 StackArray<Integer> stackArray = new StackArray<Integer>(); 5 System.out.println(stackArray.size()); 6 /* stackArray.pop();*/ 7 stackArray.push(1); 8 stackArray.push(2); 9 stackArray.push(5); 10 stackArray.push(6); 11 System.out.println(stackArray.size()); 12 System.out.println(stackArray.peek()); 13 14 15 } 16 }
5.测试结果