Day14 栈
1、一开始报错,原来是没写构造器;
2、栈的特点就是数据只能在表的一端进行插入和删除。
1 public class CharStack { 2 /** 3 * The depth. 4 */ 5 public static final int MAX_DEPTH = 10; 6 7 /** 8 * The actual depth. 9 */ 10 int depth; 11 12 /** 13 * The data 14 */ 15 char[] data; 16 17 public CharStack() { 18 depth = 0; 19 data = new char[MAX_DEPTH]; 20 }// Of the first constructor 21 22 /** 23 * Overrides the method claimed in Object, the superclass of any class. 24 */ 25 public String toString() { 26 String resultString = ""; 27 for (int i = 0; i < depth; i++) { 28 resultString += data[i]; 29 } // Of for i 30 31 return resultString; 32 }// Of toString 33 34 /** 35 * Push an element. 36 * 37 * @param paraChar The given char. 38 * @return Success or not. 39 */ 40 public boolean push(char paraChar) { 41 if (depth == MAX_DEPTH) { 42 System.out.println("Stack full."); 43 return false; 44 } // Of if 45 46 data[depth] = paraChar; 47 depth++; 48 49 return true; 50 }// Of push 51 52 /** 53 * Pop an element. 54 * 55 * @return The popped char. 56 */ 57 public char pop() { 58 if (depth == 0) { 59 System.out.println("Nothing to pop."); 60 return '\0'; 61 } // Of if 62 63 char resultChar = data[depth - 1]; 64 depth--; 65 66 return resultChar; 67 }// Of pop 68 69 /** 70 * The entrance of the program. 71 * 72 * @param args 73 */ 74 public static void main(String args[]) { 75 CharStack tempStack = new CharStack(); 76 77 for (char ch = 'a'; ch < 'm'; ch++) { 78 tempStack.push(ch); 79 System.out.println("The current stack is: " + tempStack); 80 } // Of for ch 81 82 char tempChar; 83 for (int i = 0; i < 12; i++) { 84 tempChar = tempStack.pop(); 85 System.out.println("Popped: " + tempChar); 86 System.out.println("The current stack is: " + tempStack); 87 } // Of for i 88 89 }// Of main 90 91 }// Of CharStack
今天的不难

浙公网安备 33010602011771号