package datastructure.stack;
/**
*
* Char stack. I do not use Stack because it is already defined in Java.
*
* @author WX873
*
*/
public class CharStack {
/**
* The depth.
*/
public static final int MAX_DEPTH = 10;
/**
* The data.
*/
char[] data;
/**
* The actual depth.
*/
int depth;
/**
* construct an empty char stack.
*/
public CharStack() {
// TODO Auto-generated constructor stub
depth = 0;
data = new char[MAX_DEPTH];
}//of the first constructor
/**
* Overrides the method claimed in object, the superclass of any class.
*/
public String toString() {
String resultString = "";
for (int i = 0; i < depth; i++) {
resultString += data[i];
}//of for i
return resultString;
}//of toString
/**
* Push an element.
*
* @param paraValue The given value.
* @return Success or not.
*/
public boolean push(char paraValue) {
if (depth == MAX_DEPTH) {
System.out.println("The stack is full!");
return false;
}//of if
data[depth] = paraValue;
depth++;
return true;
}//of push
/**
* pop an element.
*
* @return The poped char.
*/
public char pop() {
if (depth == 0) {
System.out.println("Nothing to pop!");
return '\0';
} //of if
char resultChar = data[depth-1];
depth--;
return resultChar;
}//of pop
public static void main(String args[]) {
CharStack tempStack = new CharStack();
for (char ch = 'a'; ch < 'm'; ch++) {
tempStack.push(ch);
System.out.println(ch);
}//of for ch
System.out.println("The current stack is: " + tempStack.toString());
//tempStack.pop();
char tempChar;
for (int i = 0; i < 12; i++) {
tempChar = tempStack.pop();
System.out.println("poped: " + tempChar);
System.out.println("The current stack is: " + tempStack);
}//of for i
}//of main
}// of class CharStack
今天的学习总结如下:
1.原博客中的代码重写了toString()方法,但是后面并没有调用该方法。测试了一下System.out.println("The current stack is: " + tempStack.toString())语句和System.out.println("The current stack is: " + tempStack)两句代码的作用是一样的。
2.自己写代码的时候犯了一个错误,对数组data进行了两次声明。代码及运行报错如下: