栈
package datastructure;
/**
* Char stack. Do not use Stack because it is already defined in Java.
*
* @author Michelle Min mitchellemin@163.com.
*/
public class CharStack {
/**
* The depth.
*/
public static final int MAX_DEPTH = 10;
/**
* The actual depth.
*/
int depth;
/**
* The data
*/
char[] data;
/**
*
* Construct an empty sequential list.
*
*/
public CharStack() {
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 paraChar
* The given char.
* @return Success or not.
*
*/
public boolean pushs(char paraChar) {
if (depth == MAX_DEPTH) {
System.out.println("Stack full.");
return false;
}// Of if
data[depth] = paraChar;
depth++;
return true;
}// Of push
/**
*
* Push an element.
*
* @param paraChar
* The given char
* @return Success or not.
*
*/
public char pop() {
if (depth == 0) {
System.out.println("Nothing to pop.");
return '\0';
}// Of pop
char resultChar = data[depth - 1];
//这里return的是第(depth-1)个字符是什么
depth--;
return resultChar;
}// Of pop
/**
*
* The entrance of the program.
*
* @param args
* Not used now.
*
*/
public static void main(String args[]) {
CharStack tempStack = new CharStack();
for (char ch = 'a'; ch < 'm'; ch++) {
tempStack.pushs(ch);
System.out.println("The current stack is: " + tempStack);
}// Of for i
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);
//由于pop处理中有length--,使tempStack最右端值索引不到,达成删除最右端的效果
}// Of for i
}// Of main
}// Of CharStack