Java棧實現:數組
1)順序棧(數組)實現:函數
*沒法創建泛型數組,採用Object對象數組,能夠輸入各類類型(不知道有什麼不妥)。spa
1 public class MySeqStack{ 2 private Object data[]; //順序棧 3 private int maxSize; //棧大小 4 private int top=-1; //棧頂 5 6 //默認構造函數,數組大小10 7 public MySeqStack(){ 8 maxSize=10; 9 data=new Object[maxSize]; 10 } 11 12 //構造函數,參數數組大小 13 public MySeqStack(int size){ 14 if(size>0){ 15 maxSize=size; 16 data=new Object[size]; 17 }else{ 18 System.out.println("wrong argument,use default max size(10)."); 19 maxSize=10; 20 data=new Object[maxSize]; 21 22 } 23 } 24 25 /**壓入棧 26 * @author truestar 27 */ 28 public void push(Object x){ 29 if(top<maxSize-1) 30 data[++top]=x; 31 else{ 32 expandSpace(); 33 push(x); 34 } 35 } 36 37 38 /** 擴展棧(數組)空間 39 * @author truestar 40 */ 41 private void expandSpace(){ 42 int maxSize0=maxSize; 43 Object[] data0=data; 44 maxSize*=2; 45 data=new Object[maxSize]; 46 System.arraycopy(data0,0,data,0,maxSize0); 47 data0=null; 48 } 49 50 51 // 判斷棧是否爲空 52 public boolean isEmpty(){ 53 return (top==-1); 54 } 55 56 //彈出棧頂 57 public Object pop(){ 58 if(!isEmpty()) 59 return data[top--]; 60 else 61 return false;//return "Stack is empty!"; 62 63 } 64 65 //返回棧頂但不刪除 66 public Object top(){ 67 if(!isEmpty()) 68 return data[top]; 69 else 70 return false; //return "Stack is empty!"; 71 72 } 73 74 }
endcode
有什麼不對或者須要補充,call me。對象
撰寫時間:2017-07-19 10:36:24blog
修改時間:2018-06-19 09:55:05class