java代碼實現:java
1 package com.guohao.arithmetics; 2 3 import java.lang.reflect.Array; 4 5 /** 6 * 棧 7 */ 8 public class Stack<T> { 9 private T[] data; //儲存棧內元素的數組 10 private int capacity; //棧的容量(棧內元素數量的最大值) 11 private int size; //棧的大小(棧內現有元素的數量) 12 private int top; //棧頂標誌器 13 14 public Stack(Class<T> type, int capacity){ 15 //爲了保證類型安全,Java中不容許直接用泛型聲明數組,如:"dataArray = new T[capacity]"是錯誤的! 16 data = (T[])Array.newInstance(type, capacity); 17 this.capacity = capacity; 18 size = 0; 19 top = -1; 20 } 21 22 /** 23 * 入棧 24 * @param element 25 * @return 26 */ 27 public boolean push(T element){ 28 if(isFull()){ 29 return false; 30 } 31 32 data[++top] = element; 33 size++; 34 return true; 35 } 36 37 /** 38 * 出棧 39 * @return 40 */ 41 public T pop(){ 42 if(isEmpty()){ 43 return null; 44 } 45 46 size--; 47 return data[top--]; 48 } 49 50 /** 51 * 判斷是否棧滿 52 * @return 53 */ 54 public boolean isFull(){ 55 return capacity==size; 56 } 57 58 /** 59 * 判斷是否棧空 60 * @return 61 */ 62 public boolean isEmpty(){ 63 return size==0; 64 } 65 66 //getter & setter 67 public T[] getData() { 68 return data; 69 } 70 71 public void setData(T[] data) { 72 this.data = data; 73 } 74 75 public int getCapacity() { 76 return capacity; 77 } 78 79 public void setCapacity(int capacity) { 80 this.capacity = capacity; 81 } 82 83 public int getSize() { 84 return size; 85 } 86 87 public void setSize(int size) { 88 this.size = size; 89 } 90 91 public int getTop() { 92 return top; 93 } 94 95 public void setTop(int top) { 96 this.top = top; 97 } 98 }