棧的特色html
所需元素數組
分析實現函數
代碼實現測試
1 public class Stack { 2 3 private int maxSize; 4 private int top; 5 private Object[] stackArr; 6 7 /** 8 * 利用構造函數初始化數組 9 * 10 * @param maxSize 11 */ 12 public Stack(int maxSize) { 13 this.maxSize = maxSize; 14 stackArr = new Object[maxSize]; 15 // 至關於棧的指針 16 top = 0; 17 } 18 19 /** 20 * 元素出棧 21 * 22 * @param i 23 */ 24 public void push(Object i) { 25 if (isFull()) { 26 throw new RuntimeException("棧已滿!"); 27 } 28 stackArr[top++] = i; 29 } 30 31 /** 32 * 元素入棧 33 * 34 * @return 35 */ 36 public Object pop() { 37 if(isEmpty()) { 38 throw new RuntimeException("空棧!"); 39 } 40 // 這裏先自減是由於top數組長度,而索引從0開始 41 return stackArr[--top]; 42 } 43 44 /** 45 * 獲取棧頂元素,只是查看,不刪除 46 * 47 * @return 48 */ 49 public Object getTop() { 50 return stackArr[top - 1]; 51 } 52 53 /** 54 * 判斷棧是否爲空 55 * 56 * @return 57 */ 58 public boolean isEmpty() { 59 return (top == 0); 60 } 61 62 /** 63 * 判斷棧是否已滿 64 * 65 * @return 66 */ 67 public boolean isFull() { 68 return (top == maxSize); 69 } 70 71 /** 72 * 回去棧元素的數量 73 * 74 * @return 75 */ 76 public int length() { 77 return top; 78 } 79 80 /** 81 * 清空棧 82 * 83 * @return 84 */ 85 public void clear() { 86 while (top != 0) { 87 pop(); 88 } 89 } 90 }
測試this
1 public class StackTest { 2 3 public static void main(String[] args) { 4 5 Stack stack = new Stack(10); 6 7 System.out.println( "棧是否爲空? " + stack.isEmpty()); 8 9 stack.push(2); 10 stack.push(1); 11 stack.push(6); 12 stack.push(3); 13 stack.push(5); 14 15 System.out.println("棧長: " + stack.length()); 16 17 System.out.println("棧頂元素: " + stack.getTop()); 18 19 System.out.println("棧滿? " + stack.isFull()); 20 21 // 清空棧 22 stack.clear(); 23 24 System.out.println( "棧是否爲空? " + stack.isEmpty()); 25 26 stack.push(2); 27 stack.push(1); 28 stack.push(6); 29 stack.push(3); 30 stack.push(5); 31 // 取出棧元素,並打印 32 while(!stack.isEmpty()){ 33 Object pop = stack.pop(); 34 System.out.print(pop + "\t"); 35 } 36 System.out.println(); 37 } 38 }
結果spa
棧是否爲空? true 棧長: 5 棧頂元素: 5 棧滿? false 棧是否爲空? true 5 3 6 1 2
總結指針
對比連接:使用鏈表實現棧code