棧的特點
- 先進后出(FILO)或者 后進先出(LIFO)
- 增刪元素皆是在棧頂操作
- 一次只能刪除一個數據項:當前棧頂元素
- 只允許訪問一個數據項:當前棧頂元素
所需元素
- 因為底層用數組實現,所以需要一個數組 stackArray
- 需要一個指向棧頂的指針top
- 需要指定數組的大小maxSize
分析實現
- 需要在創建自定義棧類的時候,就確定好一些初始化操作,例如確定數組的大小並初始化數組;
- 確定棧具有的功能:入棧push()、出棧pop()、查看棧頂元素getTop()、判空isEmpty()、判滿isFull()、判長length()、清空clear()
代碼實現
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 }
測試
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 }
結果
棧是否為空? true 棧長: 5 棧頂元素: 5 棧滿? false 棧是否為空? true 5 3 6 1 2
總結
- 底層用數組實現,簡單,但是一開始就要固定棧的大小,並且后期擴容困難;
- 插入、查找、刪除所需時間都是O(1),因為都是對棧頂元素操作。
對比鏈接:使用鏈表實現棧